Skip to content

Instantly share code, notes, and snippets.

@Xevion
Last active August 4, 2022 19:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Xevion/56e1410619a1582f83ea06610b2b5bb5 to your computer and use it in GitHub Desktop.
Save Xevion/56e1410619a1582f83ea06610b2b5bb5 to your computer and use it in GitHub Desktop.
Bitwise vs Addition in Python (1 million loops)
In [1]: def bitwise_or():
...: x = 0
...: for i in range(1, 32):
...: x |= 1 << i
...: return x
...:
In [2]: def addition():
...: x = 0
...: for i in range(1, 32):
...: x += 1 << i
...: return x
...:
In [3]: bitwise_or() == addition()
Out[7]: True
In [4]: %timeit -n 1_000_000 bitwise_or()
2.37 µs ± 58.1 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)
In [5]: %timeit -n 1_000_000 addition()
1.99 µs ± 48.7 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment