Cython taking more time than regular Python
Peter Otten
__peter__ at web.de
Tue Sep 20 07:43:44 EDT 2016
Christian Gollwitzer wrote:
> Am 20.09.16 um 09:44 schrieb Peter Otten:
>> Stefan Behnel wrote:
>>
>>> Peter Otten schrieb am 19.09.2016 um 14:55:
>>>> 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
>>>
>>> Note that this is the worst benchmark ever. Any non-dump C compiler will
>>> happily apply Young Gauß and calculate the result in constant time.
>>
>> Is that optimization useful in an actual program or just a way to cheat
>> in benchmarks?
>
> Good question, but I think this falls under "strength reduction" which
> is a useful optimization of tight loops in C.
>
> However, I'm not convinced it did succeed here. An evaluation of the
> Gauß formula would run in a few *nanoseconds* on any moddern machine. It
> may take a microsecond to call a functino from Python. a hundred
> microseconds means that the loop does run.
A quick check indeed shows linear behaviour:
In [1]: %load_ext cythonmagic
In [2]: %%cython
def sigma(int n):
cdef long i
cdef long result = 0
for i in range(n): result += i
return result
...:
In [3]: %timeit sigma(1000)
1000000 loops, best of 3: 1.04 µs per loop
In [4]: %timeit sigma(10000)
100000 loops, best of 3: 9.25 µs per loop
In [5]: %timeit sigma(100000)
10000 loops, best of 3: 91.3 µs per loop
More information about the Python-list
mailing list