[Cython] __next__ | not being able to use cpdef

Robert Bradshaw robertwb at math.washington.edu
Thu Dec 11 08:51:22 CET 2008


On Dec 10, 2008, at 2:24 AM, Jelle Feringa wrote:

>> Thing is that currently I'm working on sampling b-spline surfaces,  
>> and
> compute the curvature of such a surface.
> Basically that comes down to making a 500*500 grid of curvature  
> samples.
> Computing the curvature is really quick ( call to a SWIG wrapped
> object ).
> My code looks like:
>
> for a in xrange(1, 500):
> 	for b in xrange(1, 500):
> 		do_curvature()

Just to follow up on this, I did some timings.

%cython

def do_loop_c(f, int n, int m):
     cdef int i, j
     for i in range(n):
         for j in range(m):
             f()

cdef foo_c():
     pass

def do_loop_c_call(int n, int m):
     cdef int i, j
     for i in range(n):
         for j in range(m):
             foo_c()


%python
def foo():
     """A "fast" function to call."""
     pass

def do_loop_py(f, n, m):
     for i in xrange(n):
         for j in xrange(m):
             f()

def do_loop_empty(f, n, m):
     for i in xrange(n):
         for j in xrange(m):
             pass


sage: time do_loop_py(foo, 5000, 500)
CPU time: 0.56 s,  Wall time: 0.56 s
sage: time do_loop_empty(foo, 5000, 500)
CPU time: 0.10 s,  Wall time: 0.10 s
sage: time do_loop_c(foo, 5000, 500)
CPU time: 0.34 s,  Wall time: 0.34 s
sage: time do_loop_c_call(5000, 500)
CPU time: 0.00 s,  Wall time: 0.00 s
sage: time do_loop_c_call(5000, 50000) # 100x anything above
CPU time: 0.22 s,  Wall time: 0.22 s

The moral of the story is that the loop overhead can be reduced to  
essentially a clock cycle or two per iteration (nanoseconds) but the  
cost to call a Python function is several of orders of magnitude more  
that that.

- Robert



More information about the Cython-dev mailing list