Speed-up for loops

Nobody nobody at nowhere.com
Fri Sep 3 15:54:45 EDT 2010


On Fri, 03 Sep 2010 11:21:36 +0200, Michael Kreim wrote:

> An anonymous Nobody suggested to use Numpy. I did not do this, because I 
> am very very new to Numpy and I did not figure out a Numpy specific way 
> to do this. Maybe a Numpy expert has something for me?

The problem with giving examples is that your original example is too
contrived. Taken literally, it can be optimised to

	print imax * 10

A less contrived example would actually do something within the loop, in
order to justify the existence of the loop.

NumPy provides predefined loops which correspond to map, reduce,
accumulate and zip, for all of the standard arithmetic operators and
common mathematical functions. E.g. if your loop was:

	a = 0
	for i in xrange(imax):
	    a += i**2
	print a

the NumPy version would be:

	print numpy.sum(numpy.arange(imax)**2)

The arange() function is similar to range() but generates an array. The **
operator is implemented for arrays; sum() sums the elements of the array.

The main downside is that the intermediate array(s) must be constructed in
memory, which rules out its use for very long sequences.




More information about the Python-list mailing list