So, I have recently heard of Integer Division and that it is very fast. I have always been using Bit Shifting when I do floor(x / 2^n).
So, I have tested if which is faster Integer Division or Bit Shifting so, I made this code where it tests and compare it 100 times and find the mean:
import timeit
import statistics as stat
def compare_times(a, b):
res_a = timeit.timeit(a)
res_b = timeit.timeit(b)
c = res_a - res_b # if negative, a is faster
return c
output = []
for _ in range(100):
output.append(compare_times("5 >> 1", "5 // 2"))
print (stat.mean(output))
And the result is positive, meaning b is faster. Isn't bit shifting working directly at the bit of the number? Why is it slower than Integer Division?
I tested another thing to see if it is because I chose 5, so:
import timeit
import statistics as stat
import random
def compare_times(a, b):
res_a = timeit.timeit(a)
res_b = timeit.timeit(b)
c = res_a - res_b # if negative, a is faster
return c
output = []
for _ in range(100):
number = random.randrange(5000, 50001)
output.append(compare_times(f"{number} >> 1", f"{number} // 2"))
print (stat.mean(output))
which also outputted positve.
The only time I see a (bit shift) is faster than Integer Division is when in floor(x / 2^n), n >= 2.
So, ultimately, how does Integer Division work? And why is it faster than Bit Shift in terms of smaller numbers?