efficiency of range() and xrange() in for loops
Felipe Almeida Lessa
felipe.lessa at gmail.com
Wed Apr 5 22:32:46 EDT 2006
Em Qua, 2006-04-05 às 19:15 -0700, Alex Martelli escreveu:
> Steve R. Hastings <steve at hastings.org> wrote:
> ...
> > Actually, for many uses of "for i in (range|xrange)", you only need the
> > value of i, and you aren't doing anything with the integer object. You
>
> Then, the speediest approach may be completely different:
>
> import itertools
>
> for i in itertools.repeat(None, N):
> ...
>
>
> Remember, when you're thinking "blazing speed", think itertools.
Hmmm...
>>> min(Timer('for i in xrange(100000): pass').repeat(3, 1000))
6.7740321159362793
>>> min(Timer('for i in itertools.repeat(None, 100000): pass',
setup='import itertools').repeat(3, 1000))
5.6378099918365479
>>> min(Timer('for i in xrange(100): pass').repeat(3, 1000))
0.0071630477905273438
>>> min(Timer('for i in itertools.repeat(None, 100): pass',
setup='import itertools').repeat(3, 1000))
0.0065851211547851562
It *is* faster, but by a small margin. Considering that it is IMHO less
readable, I'd use it just for *very* big loops, or in functions in
hotspots.
Anyway, it's always good to remember about itertools, it's a great
module that some people don't even know.
Cheers,
--
Felipe.
More information about the Python-list
mailing list