python loops

Jay jaysherby at gmail.com
Sat Sep 9 00:28:24 EDT 2006


Here are my benchmarks for those interested in version 2.4.3

jsherby at montauk:~$ python -V
Python 2.4.3
jsherby at montauk:~$ python -mtimeit 'for x in range(1000):pass'
10000 loops, best of 3: 64.2 usec per loop
jsherby at montauk:~$ python -mtimeit 'for x in xrange(1000):pass'
10000 loops, best of 3: 50.5 usec per loop
jsherby at montauk:~$ python -mtimeit -s'y=range(1000)' 'for x in y:pass'
10000 loops, best of 3: 68.2 usec per loop
jsherby at montauk:~$ python -mtimeit -s'y=xrange(1000)' 'for x in y:pass'
10000 loops, best of 3: 51.4 usec per loop
jsherby at montauk:~$ python -mtimeit -s'from itertools import repeat'
'for x in repeat(None, 1000): pass'
10000 loops, best of 3: 45.6 usec per loop
jsherby at montauk:~$

Alex Martelli wrote:
> 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