for loop with variable step not optimized

39 views
Skip to first unread message

Josh Ayers

unread,
May 18, 2013, 8:01:09 PM5/18/13
to cython...@googlegroups.com
I just noticed that a for-loop using the standard Python range construct isn't optimized to C-code if the step is a run-time variable.  It is optimized if the step parameter is a compile-time constant, or if the old Pyrex style for-loop syntax is used.  I tested with Cython 0.18 and 0.19.1 and both behaved the same way.

Here's a minimal example.

DEF STEP = 2

def loops():
    cdef int i, start = 0, stop = 10, step = 2

    for i in range(start, stop, step): # generates Python loop
        print(i)

    for i in range(start, stop, STEP): # generates C loop
        print(i)

    for i from start <= i < stop by step: # generates C loop
        print(i)

Is this a bug?

Thanks,
Josh Ayers

Robert Bradshaw

unread,
May 19, 2013, 2:43:32 AM5/19/13
to cython...@googlegroups.com
If step is a runtime variable, it doesn't know what the stop condition
should be (which depends on the sign of step). It could of course
still be done by adding a bit more runtime code.
> --
>
> ---
> You received this message because you are subscribed to the Google Groups
> "cython-users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to cython-users...@googlegroups.com.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>

Josh Ayers

unread,
May 19, 2013, 4:14:09 PM5/19/13
to cython...@googlegroups.com


On Saturday, May 18, 2013 11:43:32 PM UTC-7, Robert Bradshaw wrote:
If step is a runtime variable, it doesn't know what the stop condition
should be (which depends on the sign of step).

That makes sense - thanks for the explanation.  And in the case of the Pyrex syntax, the stop condition is indicated by using a less than or greater than sign.
 
It could of course
still be done by adding a bit more runtime code.
 
You could also check the type of the step variable.  If it's unsigned, step is guaranteed to be positive.

Stefan Behnel

unread,
Jun 2, 2013, 4:00:13 AM6/2/13
to cython...@googlegroups.com
Josh Ayers, 19.05.2013 22:14:
nit-pick: non-negative, i.e. there's still an additional error case for 0
that would have to be handled at runtime.

Stefan

Reply all
Reply to author
Forward
0 new messages