Very slow cython classes?

This code that contains the cython classes:

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 so after compiling into a python extension:

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

and prints 207.374788046 (Seconds)

but pure python version (only with function and call) works in ~ 77s and cython code without class structure works in ~ 10.2s

class-less version in 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:

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 very slow compared to functional style programming in cython. Obviously, something is wrong in my cython class code. How can I improve my speed?

To summarize the test results:

Cython Class: 206s

Cython: 10.2s

python: 77s

+5
source share
1 answer

declare the type of local variable n:

cdef long n = self.n
+8

All Articles