46 lines
1.3 KiB
Python
46 lines
1.3 KiB
Python
#!/usr/bin/python3
|
|
|
|
from timeit import timeit
|
|
import random
|
|
|
|
BENCHMARK_COUNT = 180
|
|
SUPERTESTS = 90
|
|
MAX_SHIFT_VALUE = 18
|
|
SHIFT_VALUE_DIVIDER = SUPERTESTS // MAX_SHIFT_VALUE
|
|
|
|
op_and = lambda a, b: a & (b - 1)
|
|
op_mod = lambda a, b: a % b
|
|
|
|
timeit_macro = lambda func_name, number: timeit(
|
|
f"%s(random.randint(0, 2 ** 32 - 1), 1 << ({number} // SHIFT_VALUE_DIVIDER))" % func_name,
|
|
setup="from __main__ import %s\nimport random" % func_name,
|
|
number=number,
|
|
)
|
|
|
|
if __name__ == "__main__":
|
|
print(
|
|
f"Testing performance of modulo and bitwise AND remainder methods for binary divisors from 1 to {1 << (BENCHMARK_COUNT * (SUPERTESTS - 1) // SHIFT_VALUE_DIVIDER)}:"
|
|
)
|
|
|
|
time1_total = 0
|
|
time2_total = 0
|
|
for i in range(SUPERTESTS):
|
|
bench_now = BENCHMARK_COUNT * i
|
|
time1 = timeit_macro("op_and", bench_now)
|
|
time2 = timeit_macro("op_mod", bench_now)
|
|
time1_total += time1
|
|
time2_total += time2
|
|
|
|
time1_avg = time1_total / SUPERTESTS
|
|
time2_avg = time2_total / SUPERTESTS
|
|
|
|
print(f"Method #1 (AND operator):\t{time1_avg} seconds")
|
|
print(f"Method #2 (MOD operator):\t{time2_avg} seconds")
|
|
|
|
if time1 < time2:
|
|
print("Method #1 is faster")
|
|
elif time1 > time2:
|
|
print("Method #2 is faster")
|
|
else:
|
|
print("Methods have similar performance")
|