Speed-up for loops

Hrvoje Niksic hniksic at xemacs.org
Thu Sep 2 16:03:01 CEST 2010

Michael Kreim <michael at perfect-kreim.de> writes:

> Are there any ways to speed up the for/xrange loop?
> Or do I have to live with the fact that Matlab beats Python in this
> example?

To a point, yes.  However, there are things you can do to make your
Python code go faster.  One has been pointed out by Peter.

Another is that Python treats numbers as regular heap objects, so
creating a bunch of unneeded integers by xrange slows things down
(despite allocation of integer objects being heavily optimized).  For
this reason, you may want to change xrange(1000000000) to
itertools.repeat(None, 1000000000).

$ python -m timeit -s 'from itertools import repeat' 'for _ in repeat(None, 100000): pass'
1000 loops, best of 3: 1.71 msec per loop
$ python -m timeit -s 'from itertools import repeat' 'for _ in xrange(100000): pass'
100 loops, best of 3: 2.43 msec per loop

More information about the Python-list mailing list