[Tutor] optimization: faster than for

Kent Johnson kent37 at tds.net
Sun Jul 1 14:01:21 CEST 2007

elis aeris wrote:
> x = 0
> y = 0
> for x in xrange(1,1024,1):
>     for y in xrange(1,768,1):
>         rgb = image.getpixel((10, 12))
> Luke said there is a faster way to do  image.getpixel((10, 12))
> so i am still waiting on that, 
> the above has been improved many times and it's a lot faster than while, 
> I am trying to find out if there are any more new ways.

The problem is, you are making a very fast loop to do nothing. Your real 
code will have to do something and it will have different bottlenecks 
and different opportunities for optimization than this loop. Really what 
you are doing now is finding the fastest way to write loop code.

One think that will help though is to make all the variables used in the 
loop be local. Try this:

x = 0
y = 0
xrange_ = xrange
i_getpixel = image.getpixel

for x in xrange_(1,1024,1):
     for y in xrange_(1,768,1):
         rgb = i_getpixel((10, 12))

Here is a recipe that will do this kind of optimizations automatically:

You can also try optimizing your code with psyco, if you are running on 
an Intel box, or use pyrex or ShedSkin to compile part of your code to 
an extension module.


More information about the Tutor mailing list