Skip to main content
 首页 » 编程设计

python之为什么 Cython Decorator 版本比 Cython Pyx 版本慢

2025年05月04日8jirigala

我正在尝试各种方法在 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 也不支持递归。