[OT] Bit twiddling homework
Peter J. Holzer
hjp-python at hjp.at
Sat Jul 21 14:17:57 EDT 2018
On 2018-07-20 19:13:44 +1000, Chris Angelico wrote:
> On Fri, Jul 20, 2018 at 7:00 PM, Brian Oney via Python-list
> <python-list at python.org> wrote:
> > That's right I had forgotten about that. Thank you for the quick answer.Some fun:$ ipythonPython 2.7.13 (default, Nov 24 2017, 17:33:09) ...In : j = 16; i = 1
> > In : print(i+j); print(i|j)1717
> > In : %timeit i+j10000000 loops, best of 3: 65.8 ns per loop
> > In : %timeit i|j10000000 loops, best of 3: 73 ns per loop
> > In : %timeit 16|110000000 loops, best of 3: 28.8 ns per loop
> > In : %timeit 16+110000000 loops, best of 3: 28.8 ns per loop
> > I wonder why the difference between  and . My mental ranking of speed of operations tells me it should be the other way around.
> > Are 16|1 and 16+1 internally the same operation (for integers)?
> What you're seeing is nothing but noise. With numbers this low, you
> can't really judge anything.
Also, Brian is timing Python operations here, not CPU operations. In
order to execute an arithmetic or logical operation, the Python
interpreter has to execute dozens or hundreds of CPU operations. So the
single ADD or OR somewhere in the middle is swamped by other
It is possible that the code performing a numeric addition is a bit
better optimized than the code performing a bitwise or. But looking at
the source code that doesn't seem to be the case.
Might be just an accident, although the difference is remarkably
Anybody have a CPU emulator handy to trace this clock by clock? ;-)
_ | Peter J. Holzer | we build much bigger, better disasters now
|_|_) | | because we have much more sophisticated
| | | hjp at hjp.at | management tools.
__/ | http://www.hjp.at/ | -- Ross Anderson <https://www.edge.org/>
-------------- next part --------------
A non-text attachment was scrubbed...
Size: 833 bytes
Desc: not available
More information about the Python-list