Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitwise or "|" versus addition "+" for positive powers of two in Python

Let's consider this specific case in which I want to pass a set of some object's statuses. For convenience and flexibility (or perhaps arbitrarily) I chose to use binary statuses which will be then concatenated using bitwise or "|" before I pass them around:

status_a = 0b1
status_b = 0b10
status_c = 0b100

statuses_to_pass = status_a | status_c  # 0b101

Then I realized that in this case I could use addition arithmetic operator "+" as well:

status_a | status_c == status_a + status_c  
#             0b101 == 0b101  -->  True

Of course this is true when statuses are positive powers of two; there are also some other caveats like:

status_a | status_c | status_c == status_a + status_c + status_c  
#                        0b101 == 0b1001  -->  False

But let's assume I stay within the limitations - are there any reasons why bitwise operator would be better than arithmetic one? Something under the Python's hood? Which one is faster? Or maybe there are any other side effects I didn't think of?

like image 451
Stanowczo Avatar asked Apr 03 '19 14:04

Stanowczo


1 Answers

Experiments with timeit suggest that adding is faster in these cases:

import timeit
import statistics
times = {"+": [], "|": []}

for x in range(10):
    for y in range(x+1, 10):
        for op in "+|":
            t = timeit.timeit(stmt="x {} y".format(op), setup="x=2**{};y=2**{}".format(x, y))
            times[op].append(t)


statistics.mean(times["+"])  # 0.029464346377385986
statistics.mean(times["|"])  # 0.04432822428643703
like image 131
L3viathan Avatar answered Sep 19 '22 11:09

L3viathan