Cython : pure C loop optimization

cython, loops, optimization, python

Solution

The docs do mention this:

Automatic range conversion

This will convert statements of the form for i in range(...) to for i from ... when i is any cdef’d integer type, and the direction (i.e. sign of step) can be determined.

I suppose Cython wants to know the sign of step at compile time in order to generate `<` or `>` in the C loop's end condition.

See also Ticket #546 on Cython Trac

Problem

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?

Original source