user5198
user5198

Reputation: 547

very slow cython classes?

This code which contains 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 like this after compiling to 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 it prints out 207.374788046 (Seconds)

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

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

To summarise the benchmark results:

Cython class : 206s

Cython : 10.2s

python : 77s

Upvotes: 6

Views: 3089

Answers (1)

HYRY
HYRY

Reputation: 97291

declare a type for local variable n:

cdef long n = self.n

Upvotes: 9

Related Questions