此代码包含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(秒)
但是纯python版本(只有函数和对它的调用)运行在~77s 没有类结构的cython代码在~10.2s中运行
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"
Python版本:
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
Cython:10.2s
python:77s
答案 0 :(得分:8)
声明局部变量n的类型:
cdef long n = self.n