我正在尝试各种方法在 Cython 中编写阶乘函数。首先我在 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)
然后我在 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)
令我惊讶的是,这两个版本的运行时间差异巨大:
%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
最佳答案
您需要一个@cython.compile
来实际编译代码。但是,@cython.compile
似乎既不支持 cython.cfunc
也不支持递归。
关于python - 为什么 Cython Decorator 版本比 Cython Pyx 版本慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20484804/