Running speed of "cimported" function

28 views
Skip to first unread message

Hongduo Sun

unread,
Apr 20, 2018, 7:26:50 AM4/20/18
to cython-users
I have the example as follows:

test.pyx:
cdef test_func(long i):
    cdef long j
    for j in xrange(i):
        j=i

test.pxd:
cdef test_func(long i)

---------------------------------------------

test1.pyx:
import test
for i in xrange(10000000):
    test.test_func(1000000000000000)

test2.pyx:
from test cimport test_func
for i in xrange(10000000):
    test_func(1000000000000000)
-------------------------------------------------

When running test1 and test2, I found test1 is about 20 times faster than test2.
In my personal perspective, I suppose these two should running with similar speed.
Do anyone have any idea about what caused the difference?

Stefan Behnel

unread,
Apr 20, 2018, 7:34:37 AM4/20/18
to cython...@googlegroups.com
Am 20. April 2018 11:19:32 MESZ schrieb Hongduo Sun:
>I have the example as follows:
>
>test.pyx:
>cdef test_func(long i):
> cdef long j
> for j in xrange(i):
> j=i

Note that this is useless code. The C Compiler will discard it. Just use an empty function.


>test.pxd:
>cdef test_func(long i)
>
>---------------------------------------------
>
>test1.pyx:
>import test
>for i in xrange(10000000):
> test.test_func(1000000000000000)

This cannot work. Your actual code is probably different, or you forgot to rebuild after the last change, or something like that.


>test2.pyx:
>from test cimport test_func
>for i in xrange(10000000):
> test_func(1000000000000000)
>-------------------------------------------------
>
>When running test1 and test2, I found test1 is about 20 times faster
>than
>test2.
>In my personal perspective, I suppose these two should running with
>similar
>speed.
>Do anyone have any idea about what caused the difference?

Question is: what did you want to benchmark?

Stefan

Hongduo Sun

unread,
Apr 23, 2018, 7:36:12 AM4/23/18
to cython-users
Hi Stefan,

Sorry for the mistake, let's make it more clearly.

Suppose I have two cython modules, module_A and module_B, and in module_B, I want to invoke "function_a" which is defined in module_A.

Approach 1:
module_A.pyx:
dic = {'A':123,'B':456}
cpdef function_a(str key):
    print dic[key]

module_B.pyx
import module_A
module_A.function_a('A')

Approach 2:
module_A.pyx:
dic = {'A':123,'B':456}
cdef function_a(str key):
    print dic[key]

module_B.pyx:
from module_A cimport funciton_a
function_a('A')

From my perspective, approach 2 should be faster than approach 1 since it's C function, is it right?
Is there any case a cpdef defined funciton shows better speed perfomance than a cdef defined function with same content?

Thanks,
Hongduo
Reply all
Reply to author
Forward
0 new messages