On May 12, 2009, at 9:47 PM, Mohamed Lrhazi wrote:

> On Wed, May 13, 2009 at 12:31 AM, Chris Colbert  
> <[email protected]> wrote:
>> If your making lots of rapid calls to short running functions in the
>> C-library, then you may start to feel the ctypes overhead.
>
> That's what I was afraid to hear..

Hopefully after using Cython a bit, you're fears will quickly go  
away :).

> What I was hoping to hear is "Oh
> no, ctypes is all C anyways, and will perform just the same as Cython"

A simple benchmark:

import ctypes
libm = ctypes.cdll.LoadLibrary("libm.dylib") # platform dependent...
def ctypes_sum(N):
     lib_sqrt = libm.sqrt
     lib_sqrt.argtypes = (ctypes.c_double,)
     lib_sqrt.restype = ctypes.c_double
     s = 0
     for i in range(N):
         s += lib_sqrt(i)
     return s

%cython
cdef extern from "math.h":
     double sqrt(double)

def cython_sum(long N):
     cdef int i
     cdef double s=0
     for i in range(N):
         s += sqrt(i)
     return s


 >>> time ctypes_sum(10**6)
666666166.4588418
Time: CPU 1.13 s, Wall: 1.14 s

time cython_sum(10**6)
666666166.4588418
Time: CPU 0.03 s, Wall: 0.03 s

Of course if you're calling a c function, waiting 1 second for the  
result, and then looking at the return value, the overhead won't make  
a difference at all. On the other extreme, as in the example above,  
the overhead will absolutely kill you.

That being said, ctypes is a very cool module and does have its place.

- Robert
_______________________________________________
Cython-dev mailing list
[email protected]
http://codespeak.net/mailman/listinfo/cython-dev

Reply via email to