Why is this so much faster?

Keir Rice keirrice at gmail.com
Thu Jun 2 18:07:44 EDT 2011


Hi All,

The following function was showing up in my profiles as a large bottle neck:

# Slow version
def RMSBand(self, histogram):
	"""Calculates the root-mean-squared value for the given colour stream histogram."""
	intermediateResult = map(lambda (i, h): h*(i**2), zip(histogram, range(255)))
	totalSum = sum(intermediateResult)
	
	# calculate rms
	return math.sqrt(totalSum / self.Area())

So after a bit of trial and error I came up with the following function which is a lot faster:

# Fast version
def RMSBand(self, histogram):
	"""Calculates the root-mean-squared value for the given colour stream histogram."""
	totalSum = 0
	for i, h in enumerate(histogram):
		totalSum += h*(i**2)
	
	# calculate rms
	return math.sqrt(totalSum / self.Area())

My question is why is the second method so much faster?
Is it the removal of the extra function calls?
Is it skipping the creation of a list?
Do the basic arithmetic operators get pushed up into C code?

Any insights into the whats really happening behind the scenes would be appreciated.

Keir



More information about the Python-list mailing list