# Speed-up for loops

Philip Bloom pbloom at crystald.com
Thu Sep 2 20:12:50 CEST 2010

```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).

-----Original Message-----
From: python-list-bounces+pbloom=crystald.com at python.org
[mailto:python-list-bounces+pbloom=crystald.com at python.org] On Behalf Of
Nobody
Sent: Thursday, September 02, 2010 9:05 AM
To: python-list at python.org
Subject: Re: Speed-up for loops

On Thu, 02 Sep 2010 12:02:40 +0200, Michael Kreim wrote:

> I was comparing the speed of a simple loop program between Matlab and
> Python.

> imax = 1000000000
> a = 0
> for i in xrange(imax):
>      a = a + 10
> print a

> Are there any ways to speed up the for/xrange loop?

Sure; the above can be reduced to just:

print imax * 10
;)

More seriously, if you're comparing against Matlab, you should look at
NumPy. If there's a reasonably direct approach using NumPy, it will be
much quicker than a Python "for" loop (in a sense, NumPy is a library of
useful "for" loops implemented in C).

Even a fairly indirect NumPy approach is often quicker than pure Python.

--
http://mail.python.org/mailman/listinfo/python-list

______________________________________________________________________
This email has been scanned by the MessageLabs
______________________________________________________________________

______________________________________________________________________
This email has been scanned by the MessageLabs
______________________________________________________________________

```