Cython taking more time than regular Python

Peter Otten __peter__ at web.de
Mon Sep 19 08:55:28 EDT 2016


Arshpreet Singh wrote:

> Hope this is good place to  ask question about Cython as well.
> Following code of mine is taking 2.5 times more time than Native Python
> code:
> 
> %%cython
> import numpy as np
> a = np.array([])
> def large_sum2(int num_range):
>     np.append(a,[i for i in xrange(num_range)])
>     return a.sum
> 
> %timeit large_sum2(100000)
> 10 loops, best of 3: 19 ms per loop
> 
> on the other side python takes much less time:
> 
> def large_sum(num_range):
>     return sum([i for i in xrange(num_range)])
> 
> %timeit large_sum(100000)
> 100 loops, best of 3: 7 ms per loop

But the two versions aren't the same! 

If you compare similar code:

In [2]: %%cython
def sigma(n): return sum(i for i in range(n))
   ...: 

In [3]: def tau(n): return sum(i for i in range(n))

In [4]: %timeit sigma(100000)
100 loops, best of 3: 8.34 ms per loop

In [5]: %timeit tau(100000)
100 loops, best of 3: 12.7 ms per loop

And if you decide to go lowlevel (there may be smarter ways, but I'm a 
complete amateur with Cython):

In [7]: %%cython
def omega(int n):
    cdef long i
    cdef long result = 0
    for i in range(n): result += i
    return result
   ...: 

In [8]: %timeit omega(100000)
10000 loops, best of 3: 91.6 µs per loop

In [9]: assert omega(100000) == tau(100000) == sigma(100000)





More information about the Python-list mailing list