Why is this so much faster?

Peter Otten __peter__ at web.de
Fri Jun 3 04:03:27 EDT 2011


Keir Rice wrote:

> Ian, I was basing my code off Fredrik Lundh post on comparing images.
> http://effbot.org/zone/pil-comparing-images.htm

> return math.sqrt(sum([h*i*i for i,h in enumerate(histogram)]) /
> self.Area())
> 
> Ran at the same speed as my 'fast' version and without the square brackets
> was slower.

It looks like len(histogram) will always be 256. If so, you can factor out 
[i*i for i in range(256)]. For number-crunching tasks considering numpy 
might also be a good idea:

# untested
import numpy

deltas = numpy.arange(256, dtype=float)
squares = deltas * deltas

class Whatever:
    def RMSBand(self, histogram):
        return math.sqrt((squares*histogram).sum()/self.Area())

If it works this should be quite fast.




More information about the Python-list mailing list