Fatest standard way to sum bytes (and their squares)?

Hrvoje Niksic hniksic at xemacs.org
Sun Aug 12 14:50:33 EDT 2007


Erik Max Francis <max at alcyone.com> writes:

> So far the fastest way I've found is using the `sum` builtin and
> generators::
>
> 	ordinalSum = sum(ord(x) for x in data)
> 	ordinalSumSquared = sum(ord(x)**2 for x in data)

For ordinalSum, using imap is almost twice as fast:

$ python -m timeit -s 'data=[chr(x) for x in xrange(256)]' 'sum(ord(x) for x in data)'
10000 loops, best of 3: 92.4 usec per loop
$ python -m timeit -s 'data=[chr(x) for x in xrange(256)]; from itertools import imap' 'sum(imap(ord, data))'
10000 loops, best of 3: 55.4 usec per loop

Of course, that optimization doesn't work for the squared sum; using a
lambda only pessimizes it.



More information about the Python-list mailing list