[OT] Bit twiddling homework

Chris Angelico rosuav at gmail.com
Fri Jul 20 05:13:44 EDT 2018


On Fri, Jul 20, 2018 at 7:00 PM, Brian Oney via Python-list
<python-list at python.org> wrote:
> 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)?

What you're seeing is nothing but noise. With numbers this low, you
can't really judge anything. In fact, operations 5 and 6 are probably
just looking up constants that got calculated once, so they're
literally proving nothing at all.

Even at the CPU level, you'll generally find that adding two numbers
takes the same amount of time as bitwise Or, mainly because both of
them take a single clock cycle. (Proving that they actually DON'T take
the same amount of time requires a fairly deep understanding of the
internal workings of the chip.) Definitely at the Python level, the
costs are virtually identical. Don't do bitwise operations for the
sake of performance; do them because they clearly and adequately
describe what you're doing. :)

ChrisA


More information about the Python-list mailing list