简体   繁体   English

非常慢的cython课程?

[英]very slow cython classes?

This code which contains cython classes: 此代码包含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"

which I called like this after compiling to a python extension: 编译成python扩展后我打电话给这个:

from time import time
t1 = time()
import factors_class
ben = factors_class.Bench(1000000007)
print ben.factors()
t2 = time()
print t2 - t1

and it prints out 207.374788046 (Seconds) 它打印出207.374788046(秒)

but the pure python version (with just the function and a call to it) runs in ~ 77s and a cython code without class structure runs in ~ 10.2s 但是纯python版本(只有函数和对它的调用)在~77s运行,没有类结构的cython代码在~10.2s运行

class-less version in cython: 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 version: Python版本:

def factors(n):
    fac = 0
    for i in xrange(2, n):
        if n % i == 0:
            fac += 1

    return fac

print factors(10000007)

I want to use cython classes for my library but, they seem to be very slow compared to functional style programming in cython. 我想为我的库使用cython类,但是与cython中的函数式编程相比,它们似乎非常慢。 Clearly something is wrong in my cython class code. 显然我的cython类代码有问题。 How can I improve its speed? 我怎样才能提高它的速度?

To summarise the benchmark results: 总结基准测试结果:

Cython class : 206s Cython课程:206s

Cython : 10.2s Cython:10.2s

python : 77s python:77s

声明局部变量n的类型:

cdef long n = self.n

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM