Speed-up for loops

Michael Kreim michael at perfect-kreim.de
Thu Sep 2 13:16:08 CEST 2010


Peter Otten wrote:
> Move it into a function; this turns a and i into local variables.
> 
> def f():
>     imax = 1000000000
>     a = 0
>     for i in xrange(imax):
>         a = a + 10
>     print a
> f()

Wow. It is still slower than Matlab, but your suggestion speeds up the 
code by ca 50%.
But I do not understand why the change of a global to a local variable 
gives such a big difference.


$ cat addition.py
imax = 1000000000
a = 0
for i in xrange(imax):
     a = a + 10
print a

$ cat additionOtten.py
def f():
     imax = 1000000000
     a = 0
     for i in xrange(imax):
         a = a + 10
     print a
f()

$ /usr/bin/time --verbose python addition.py
10000000000
         Command being timed: "python addition.py"
         User time (seconds): 110.52
         System time (seconds): 0.01
         Percent of CPU this job got: 98%
         Elapsed (wall clock) time (h:mm:ss or m:ss): 1:52.76
	[...]

$ /usr/bin/time --verbose python additionOtten.py
10000000000
         Command being timed: "python additionOtten.py"
         User time (seconds): 56.38
         System time (seconds): 0.00
         Percent of CPU this job got: 99%
         Elapsed (wall clock) time (h:mm:ss or m:ss): 0:56.64
	[...]



More information about the Python-list mailing list