title: very slow cython classes?
body: <p>This code which contains cython classes:</p>
  
  <pre><code>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"
  </code></pre>
  
  <p>which I called like this after compiling to a python extension:</p>
  
  <pre><code>from time import time
  t1 = time()
  import factors_class
  ben = factors_class.Bench(1000000007)
  print ben.factors()
  t2 = time()
  print t2 - t1
  </code></pre>
  
  <p>and it prints out 207.374788046 (Seconds)</p>
  
  <p>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</p>
  
  <p>class-less version in cython:</p>
  
  <pre><code>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"
  </code></pre>
  
  <p>Python version:</p>
  
  <pre><code>def factors(n):
      fac = 0
      for i in xrange(2, n):
          if n % i == 0:
              fac += 1
  
      return fac
  
  print factors(10000007)
  </code></pre>
  
  <p>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?</p>
  
  <p>To summarise the benchmark results:</p>
  
  <p>Cython class :   206s</p>
  
  <p>Cython       :   10.2s</p>
  
  <p>python       :   77s</p>