Which is faster?

Raymond Hettinger python at rcn.com
Sat Aug 30 18:33:36 EDT 2008


On Aug 29, 9:26 pm, cnb <circularf... at yahoo.se> wrote:
> def av_grade(self):
>      return sum(review.grade for review in self.reviews) / \
>               len(self.reviews)

Minor point.  Consider making the divisor:  float(len(self.reviews)).
It would be a bummer to throw-off the average because of floor
division.

Also consider an itertools approach:
    sum(itertools.imap(operator.itemgetter('review'), self.reviews))

BTW, the sum() in Py2.6 is *much* faster than before.  It should run
circles around any other approach.

As Effbot says, if you really care about speed, then just time both
approaches.  However, it's a good run of thumb that builtins are hard
to beat by simulating them in pure python (unless you're using Psyco
as an optimizer).


Raymond



More information about the Python-list mailing list