Skip to content

Commit b259603

Browse files
committed
Add script to compare sorting algorithm runtimes
1 parent 3e2f139 commit b259603

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

compare.py

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
#!/usr/bin/env python3
2+
3+
import random
4+
import sorting_algorithms
5+
import sys
6+
import timeit
7+
8+
from typing import Tuple
9+
10+
algorithm1 = getattr(sorting_algorithms, sys.argv[1])
11+
algorithm2 = getattr(sorting_algorithms, sys.argv[2])
12+
trials: int = int(sys.argv[3])
13+
array_len: int = int(sys.argv[4])
14+
15+
16+
def run_trials() -> Tuple[float, float]:
17+
algorithm1_time_total = 0.0
18+
algorithm2_time_total = 0.0
19+
20+
for _ in range(trials):
21+
random_array = [random.random() for _ in range(array_len + 1)]
22+
random_array_copy = random_array[:]
23+
algorithm1_time_total += timeit.timeit(
24+
lambda: algorithm1(random_array), number=1)
25+
algorithm2_time_total += timeit.timeit(
26+
lambda: algorithm2(random_array_copy), number=1)
27+
28+
return (algorithm1_time_total, algorithm2_time_total)
29+
30+
31+
def main():
32+
algorithm1_time_total, algorithm2_time_total = run_trials()
33+
34+
print(f"Trials: {trials}")
35+
print(f"Input Length: {array_len}")
36+
print("\nAverage Time:")
37+
print(f"{algorithm1.__name__}: {algorithm1_time_total/trials:.6f}")
38+
print(f"{algorithm2.__name__}: {algorithm2_time_total/trials:.6f}")
39+
40+
if algorithm1_time_total > algorithm2_time_total:
41+
ratio = algorithm1_time_total / algorithm2_time_total
42+
print(
43+
f"\n{algorithm2.__name__} ran {ratio:.1f} times faster than {algorithm1.__name__}.")
44+
else:
45+
ratio = algorithm2_time_total / algorithm1_time_total
46+
print(
47+
f"\n{algorithm1.__name__} ran {ratio:.1f} times faster than {algorithm2.__name__}.")
48+
49+
50+
main()

0 commit comments

Comments
 (0)