Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #6893

Re: Why is this so much faster?

From Terry Reedy <tjreedy@udel.edu>
Subject Re: Why is this so much faster?
Date 2011-06-02 19:04 -0400
References <8bccb0f0-4c1a-4ec8-91b4-4f420d0d8eb9@glegroupsg2000goo.googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.2407.1307055911.9059.python-list@python.org> (permalink)

Show all headers | View raw


On 6/2/2011 6:07 PM, Keir Rice wrote:
> 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?

Yes. Map is only 'fast' when one already has a function and is going to 
call it repeatedly regardless of the other code. When one has an 
expression, wrapping it as a function to use map is surely slower. Have 
you tried

   return math.sqrt(sum([h*i*i for i,h in enumerate(histogram)])
     / self.Area())

or same without [] brackets?

i*i should be faster than i**2 in any version.

> Is it skipping the creation of a list?

A bit.

See Tim's response.

-- 
Terry Jan Reedy

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Why is this so much faster? Keir Rice <keirrice@gmail.com> - 2011-06-02 15:07 -0700
  Re: Why is this so much faster? Terry Reedy <tjreedy@udel.edu> - 2011-06-02 19:04 -0400
  Re: Why is this so much faster? Ian Kelly <ian.g.kelly@gmail.com> - 2011-06-02 17:50 -0600

csiph-web