Quoting the Cython documentation:
Cython recognises the usual Python for-in-range integer loop pattern:
for i in range(n):
...
If i is declared as a cdef integer type, it will optimise this into a pure C loop
I wrote two versions of a simple Cython function, one using the Python range
, the other one using the for-from
Pyrex notation (which is supposed to be deprecated):
def loop1(int start, int stop, int step):
cdef int x, t = 0
for x in range(start, stop, step):
t += x
return t
def loop2(int start, int stop, int step):
cdef int x, t = 0
for x from start <= x < stop by step:
t += x
return t
By looking at .c
file, I noticed that the two loops have been processed in a very different way:
The first one is actually creating a Python range, using Python objects. And it comes with 50 lines of unnecessary Python-to-C C-to-Python stuff.
The second one has been optimized into a nice pure C loop:
__pyx_t_1 = __pyx_v_stop;
__pyx_t_2 = __pyx_v_step;
for (__pyx_v_x = __pyx_v_start; __pyx_v_x < __pyx_t_1; __pyx_v_x+=__pyx_t_2) {
Am I missing something or is it a bug that I should report?
int
withunsigned int
but the results remain the same. And I have no idea how to tell Cython the sign of the step. – Bibelot