[Image-SIG] Comparison of PIL and GD speed for setting pixels through python

John Barratt jb at langarson.com.au
Tue Feb 6 02:43:58 CET 2007

Hi Douglas,

Douglas Bagnall wrote:
> um.. cache locality?  With GD you have
>   for (u=0; u<x; u++) {
>     for (v=0; v<y; v++) {
>       d[v][u] = colour;
>     }
>   }
> which goes through every row for each column, jumping back and forth in
> memory.  You need to switch the order of the loops, like you have in the
> PIL example:
>   for (u=0; u<xSize; u++) {
>     for (v=0; v<xSize; v++) {
>       data[u][v] = colour;
>     }
>   }
Ahhh, thanks, that makes sense!  The data is arranged differently in the 
two examples, but not my loops...  Changing this around swings the best 
performer around the other way.  For a 512x512 image indicative results 
now looks like :

  Method          Time (s)        Times slower than fastest
+-----+         +-------+       +------------------------+
ctypes,c,GD raw 0.00174         1.0
PIL,load/c/raw  0.00356         2.0

However, if you now exclude image creation time, the times are basically 
the same for both the c,raw methods, as would be expected. :)

> ...which, BTW, as written, would not be so successful on non-square images.
errr, yes, fixed. *red face* Thank you! :)

I've updated the code linked from here with these changes :

> However, this shows how far the benchmark has got from real world usage.
>  As Chris Barker pointed out, if you are doing any kind of work to find
> your pixels, these effects would become negligible.
Yes, true.  As I mentioned in the response to Chris's post though, there 
are cases I think where this will have a direct benefit, and if not, 
there will also often be an indirect one due to the ability to easily 
code that more complex operation in C than python, and also have it 
called efficiently direct from C.

> Have you looked at PyGame? it seems to have drawing commands too.
No, I haven't, and it may be worth looking at.  However I primarily 
wanted to look at ways to speed up CPU hogging operations in particular 
application with the likes of PIL and gd, and still be able to get the 
benefit of direct python access to the other typical 'Imaging Library' 
type methods such as drawing text, lines, etc.  I suppose PyGame will 
have a lot of this, but perhaps not the breadth of more traditional 
image operations that PIL, or even gd provide.

Thanks for you comments,



John Barratt - www.langarson.com.au
          Python, Zope, GIS, Weather

More information about the Image-SIG mailing list