此代码包含 cython 类:
cdef class Bench:
cdef long n
def __cinit__(self, long n):
self.n = n
cpdef int factors(self):
n = self.n
cdef int fac = 0
cdef unsigned long i
for i in range(2, n):
if n % i == 0:
fac += 1
return fac
if __name__ == "__main__":
print "hw"
在编译为 python 扩展后我这样调用:
from time import time
t1 = time()
import factors_class
ben = factors_class.Bench(1000000007)
print ben.factors()
t2 = time()
print t2 - t1
它打印出 207.374788046 (Seconds)
但是纯 python 版本(只有函数和对它的调用)在 ~ 77 秒内运行,没有类结构的 cython 代码在 ~ 10.2 秒内运行
cython 中的无类版本:
cdef int factors(unsigned long n):
cdef int fac = 0
cdef unsigned long i
for i in range(2, n):
if n % i == 0:
fac += 1
return fac
print factors(1000000007)
if __name__ == "__main__":
print "hw"
蟒蛇版本:
def factors(n):
fac = 0
for i in xrange(2, n):
if n % i == 0:
fac += 1
return fac
print factors(10000007)
我想在我的库中使用 cython 类,但是与 cython 中的函数式编程相比,它们似乎非常慢。显然,我的 cython 类代码有问题。我怎样才能提高它的速度?
总结基准测试结果:
Cython 类:206s
赛通:10.2s
蟒蛇:77s