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
declare a type for local variable n:
cdef long n = self.n
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With