Speed-up for loops

Peter Otten __peter__ at web.de
Thu Sep 2 15:13:24 EDT 2010


Philip Bloom wrote:

> Uh.
 
> Try:
> Imax=1000000000
> a=0
> i=0
> While(i<imax):
>         a= a+10
>       i=i+1
> print a
 
> I suspect you will find it is way faster than using range or xrange for
> large numbers and map far more closely in the final result to what you
> are doing on matlab's side.  At least last I checked, xrange and range
> both involve iterating through an array, which is much slower in all
> cases than just doing an int vs int compare (which is what your matlab
> is doing).

How did you check? 

$ python -m timeit "for i in xrange(1000000): pass"
10 loops, best of 3: 47.5 msec per loop
$ python -m timeit "i = 0" "while i < 1000000: i += 1"
10 loops, best of 3: 152 msec per loop
$

So an empty while loop takes about three times as long as the equivalent for 
loop. Also:

"""
class xrange(object)
 |  xrange([start,] stop[, step]) -> xrange object
 |
 |  Like range(), but instead of returning a list, returns an object that
 |  generates the numbers in the range on demand.  For looping, this is
 |  slightly faster than range() and more memory efficient.
"""

Peter



More information about the Python-list mailing list