|
|
|
|
|
by BeefWellington
514 days ago
|
|
I did some testing and even in python both approaches are nearly identical in speed: def isEven_modulus(num):
return num % 2 == 0
def isEven_bit(num):
return (num & 1) == 0
import random, time
testSet = random.choices(range(0, 100), k=10)
iterations = range(1000)
print("These are our test numbers: ", testSet)
mod_start = time.perf_counter_ns()
for z in iterations:
for n in testSet:
isEven_modulus(n)
mod_end = time.perf_counter_ns()
for z in iterations:
for n in testSet:
isEven_bit(n)
bit_end = time.perf_counter_ns()
print("Modulus method: ", mod_end - mod_start, "ns")
print("Bitwise method: ", bit_end - mod_end, "ns")
There's some variance run to run but for the most part they're close enough to not matter. I do see a very small difference generally in favour of bitwise, but we're talking about a 60000ns (0.06ms) difference occasionally on 1000 runs (or about 60ns per run). Unlikely that this will be a significant bottleneck for anyone.An example: These are our test numbers: [45, 88, 55, 52, 40, 70, 62, 47, 78, 30]
Modulus method: 757341 ns
Bitwise method: 698872 ns
Possibly just a well understood and well-optimized problem. |
|