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

Hrvoje Niksic hniksic at xemacs.org
Mon Aug 13 07:25:31 EDT 2007


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

> Hrvoje Niksic wrote:
>
>> 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
>
> You're using data which is a list of chars (strings), rather than a
> string itself, which is what the format is in.  The imap
> optimization doesn't appear to work quite as dramatically well for
> me with strings instead of lists, but it certainly is an
> improvement.

I wouldn't expect to see any difference in strings and lists.  In this
simple test I get approximately the same ~1.7x speedup:

$ python -m timeit 'sum(ord(x) for x in "abcdefghijklmnopqrstuvwxyz")'
100000 loops, best of 3: 12.7 usec per loop
$ python -m timeit -s 'from itertools import imap' 'sum(imap(ord, "abcdefghijklmnopqrstuvwxyz"))'
100000 loops, best of 3: 7.42 usec per loop



More information about the Python-list mailing list