# [Tutor] back on bytes

Kent Johnson kent37 at tds.net
Sat Jul 7 13:51:27 CEST 2007

```Alan Gauld wrote:
> Surely it is easier and more obvious
> 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

.0917/.0924 = 0.99242424242424254

src \$ python -m timeit -s "nums=range(256); mults=range(1, 22)" "for i
in nums:" "  for m in mults:" "    i<<m"
1000 loops, best of 3: 564 usec per loop

src \$ python -m timeit -s "nums=range(256); mults=[1<<m for m in
range(1, 22)]" "for i in nums:" "  for m in mults:" "    i*m"
1000 loops, best of 3: 579 usec per loop

src \$ python -m timeit -s "nums=range(256); mults=[1<<m for m in
range(1, 22)]" "for i in nums:" "  for m in mults:" "    pass"
10000 loops, best of 3: 195 usec per loop

If the last timing is a reasonable estimate of the loop overhead in the
previous two, then roughly the speed difference is 579-195=384 vs
564-195=369 and shifting is 369/384.=0.9609375 the speed of multiplication.

My guess is the integer multiply in my computer recognizes this simple
case and optimizes it to a shift.

Kent
```