Speed-up for loops

Peter Otten __peter__ at web.de
Thu Sep 2 13:43:11 CEST 2010


Michael Kreim wrote:

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

Basically the local namespace is a C array where accessing an item is just 
pointer arithmetic while the global namespace is a Python dictionary. 

There may be optimisations for the latter. If you can read C have a look at 
the LOAD/STORE_FAST and LOAD/STORE_GLOBAL implementations for the gory 
details:

http://svn.python.org/view/python/trunk/Python/ceval.c?view=markup

Peter




More information about the Python-list mailing list