Speed-up for loops

Stefan Behnel stefan_ml at behnel.de
Mon Sep 6 13:20:01 CEST 2010


BartC, 06.09.2010 12:38:
> why doesn't Python 3 just accept 'xrange' as a synonym for 'range'?

Because Python 3 deliberately breaks backwards compatibility in order to 
clean up the language.


> These are just some simple tests on my particular machine and
> implementations, but they bring up some points:
>
> (1) Loop unrolling does seem to have a benefit, when the loop body is
> small.

Nobody said otherwise. However, "small" is a pretty weak characterisation 
here. And don't expect CPython to do it for you, because doing it 
automatically requires the ability to see that there are no side effects. 
It's a lot more costly to assure that than what you actually gain with the 
optimisation. As your example shows, doing this optimisation manually is 
pretty straight forward, so there isn't really a need to let the runtime do 
it for you.


> (2) Integer arithmetic seems to go straight from 32-bits to long
> integers; why not use 64-bits before needing long integers?

You are making assumptions based on Python 2, I guess. Try Python 3.1 or 
later instead, where the int and long types are unified. Also, the 
implementation is a bit more complex than you appear to be thinking. Don't 
forget that it has received serious benchmarking based optimisations.


> (3) Since the loop variable is never used, why not have a special loop
> statement that repeats code so many times?

Because special cases are not special enough to break the rules. As others 
have stated before, you can use itertools to reduce that part of the 
looping overhead, if it really hurts your concrete code. There also were 
lots of examples in this thread on different looping solutions and their 
performance differences. Any of them may fit your needs in a given situation.


> This can be very fast, since
> the loop counter need not be a Python object

It still has to count, though.

Stefan




More information about the Python-list mailing list