[Tutor] back on bytes
Alan Gauld
alan.gauld at btinternet.com
Sat Jul 7 14:13:17 CEST 2007
"Kent Johnson" <kent37 at tds.net> wrote
>> to simply shift the bits right or left using >> and << and use
>> bitwise and/or operations than do all this multiplication and
>> addition malarky. (Its also a lot faster!)
>
> Are you sure about that? With Python 2.5 on a MacBook Pro it seems
> to
> be *slightly* faster:
>
> src $ python -m timeit "5 << 21; 10 << 21; 50 << 21; 247 << 21"
> 10000000 loops, best of 3: 0.0917 usec per loop
>
> src $ python -m timeit "5 * 0x200000; 10 * 0x200000; 50 * 0x200000;
> 247
> * 0x200000"
> 10000000 loops, best of 3: 0.0924 usec per loop
OK, I really should learn not to make assumptions about
how Python works speed wise, its usually too clever for me.
In past lives I've found multiplication/addition to be a factor
of 2 or 3 times slower than shifting/ORing.
I still think it's faster to write since if you just want to
shift 7 places right you don't have to think "what's 2 ** 7?"
and then multiply by that value.
And ORing things together with a bitwise OR is usually
just a single operation whereas adding them together is
usually many clock cycles. But, lo and behold, when I try
timing that in Python addition looks to be about 10% faster
than bitwise OR which is astonishing!
Alan Gauld at xp ~
$ python -m timeit "128 | 7"
10000000 loops, best of 3: 0.146 usec per loop
Alan Gauld at xp ~
$ python -m timeit "128 + 7"
10000000 loops, best of 3: 0.115 usec per loop
I guess this relates to our discussion about moving from
C to Python, its best not to think too much about the low
level workings, just write the clearest code and trust Python
to do the right thing!
But in this case I still think the bitwise operations are
more obviously related to the task than using arithmetic
operations.
Alan G.
More information about the Tutor
mailing list