python loops

Alex Martelli aleax at mac.com
Sat Sep 9 04:53:05 CEST 2006


Tim Roberts <timr at probo.com> wrote:
   ...
> xrange used to be better.  As I understand it, that's no longer the case.

measuring is better than guessing:

brain:~/codejam alex$ python -V
Python 2.5c1
brain:~/codejam alex$ python -mtimeit 'for x in range(1000):pass'
10000 loops, best of 3: 71.9 usec per loop
brain:~/codejam alex$ python -mtimeit 'for x in xrange(1000):pass'
10000 loops, best of 3: 54 usec per loop
brain:~/codejam alex$ python -mtimeit -s'y=range(1000)' 'for x in
y:pass'
10000 loops, best of 3: 44.8 usec per loop
brain:~/codejam alex$ python -mtimeit -s'y=xrange(1000)' 'for x in
y:pass'
10000 loops, best of 3: 53.2 usec per loop
brain:~/codejam alex$ 

So: in 2.5 (2.4 too, do your own timings;-) range is better if you can
create the range once and use it repeatedly, xrange if you have to
create the range each time.  But actually:

brain:~/codejam alex$ python -mtimeit -s'from itertools import repeat'
'for x in repeat(None, 1000): pass'
10000 loops, best of 3: 41.3 usec per loop

if you don't actually need the iteration-index in the loop (you just
need to repeat the loop N times), itertools.repeat is even better (well,
if every microsecond counts, anyway;-).


Alex



More information about the Python-list mailing list