[OT] Bit twiddling homework

Brian Oney brian.j.oney at googlemail.com
Fri Jul 20 05:00:09 EDT 2018


On Fri, 2018-07-20 at 06:37 +0000, Steven D'Aprano wrote:
> On Fri, 20 Jul 2018 08:25:04 +0200, Brian Oney via Python-list wrote:
> 
> > PS: Can I twiddle bits in Python?
> 
> Yes.
> 
> These operators work on ints:
> 
>   bitwise AND:  &
>   bitwise OR:   |
>   bitwise XOR:  ^
> 
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 [1]: j = 16; i = 1
In [2]: print(i+j); print(i|j)1717
In [3]: %timeit i+j10000000 loops, best of 3: 65.8 ns per loop
In [4]: %timeit i|j10000000 loops, best of 3: 73 ns per loop
In [5]: %timeit 16|110000000 loops, best of 3: 28.8 ns per loop
In [6]: %timeit 16+110000000 loops, best of 3: 28.8 ns per loop
I wonder why the difference between [3] and [4]. 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)? 


More information about the Python-list mailing list