Ask Your Question
1

Any reason not to use cpdef for every Cython function?

asked 2012-04-18 22:32:09 +0200

chaesloc2 gravatar image

From http://docs.cython.org/src/userguide/...

Within a Cython module, Python functions and C functions can call each other freely, but only Python functions can be called from outside the module by interpreted Python code. So, any functions that you want to “export” from your Cython module must be declared as Python functions using def. There is also a hybrid function, called cpdef. A cpdef can be called from anywhere, but uses the faster C calling conventions when being called from other Cython code.

So what's the catch?

edit retag flag offensive close merge delete

2 Answers

Sort by » oldest newest most voted
2

answered 2013-04-09 17:15:34 +0200

nbruin gravatar image

Also, cpdef methods do have a little overhead because they check whether they have been overridden, even when called as cdef method. If your instance has an instance dictionary, the overhead is significant compared to normal c function calling overhead:

cython(""" cdef class A(object):
    cpdef int a(self):
        return 0
    cdef int b(self):
        return 0
    cpdef int test_a(self, long N):
        cdef long i
        for i in xrange(N):
            self.a()
        return 0
    cpdef int test_b(self, long N):
        cdef long i
        for i in xrange(N):
            self.b()
        return 0 """)

t=A()
timeit('t.test_a(10000000)')
timeit('t.test_b(10000000)')
class B(A):
    pass

s=B()
timeit('s.test_a(10000000)')
timeit('s.test_b(10000000)')

results in

25 loops, best of 3: 21.2 ms per loop
25 loops, best of 3: 15.9 ms per loop
5 loops, best of 3: 507 ms per loop
25 loops, best of 3: 15.9 ms per loop

The dictionary present on b (by subclassing) significantly slows down code that seems to run entirely at C level.

edit flag offensive delete link more
0

answered 2012-04-19 12:20:05 +0200

Volker Braun gravatar image

Wastes disk space (not really an issue nowadays). And cpdef'ing everything indiscriminately needlessly increases Python namespace clutter.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 2012-04-18 22:32:09 +0200

Seen: 6,122 times

Last updated: Apr 09 '13