[英]Why is Cython Decorator version slower than Cython Pyx version?
I am trying all sorts of ways to write the factorial function in Cython. 我正在尝试各种方式在Cython中编写阶乘函数。 First I tried the pyx file version in iPython Notebook.
首先,我在iPython Notebook中尝试了pyx文件版本。
%%file pyxfact.pyx
cdef long pyxfact(long n):
if n <=0:
return 1
else:
return n * pyxfact(n-1)
def fact(long n):
return pyxfact(n)
Then I tried the same, as least I think so, in Cython decorator, like this: 然后,我至少在Cython装饰器中尝试了相同的操作,如下所示:
%%file cydecofact.py
import cython
@cython.cfunc # equivalent to cdef, while @cython.ccall is equivalent to cpdef
@cython.returns(cython.long)
@cython.locals(n=cython.long)
def deco_fact(n):
if n <=0:
return 1
else:
return n * deco_fact(n-1)
@cython.locals(n=cython.long)
def fact(n):
return deco_fact(n)
To my surprise, the two versions have a huge run time difference: 令我惊讶的是,这两个版本在运行时间上存在巨大差异:
%timeit -n 10000 pyxfact.fact(10)
%timeit -n 10000 cydecofact.fact(10)
10000 loops, best of 3: 219 ns per loop
10000 loops, best of 3: 2 µs per loop
You need a @cython.compile
to actually compile the code. 您需要一个
@cython.compile
才能实际编译代码。 However, it looks like neither cython.cfunc
nor recursion is supported for @cython.compile
. 但是,
@cython.compile
似乎既不支持cython.cfunc
也不支持递归。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.