-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbenchmark.py
More file actions
67 lines (49 loc) · 2.02 KB
/
benchmark.py
File metadata and controls
67 lines (49 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import sys
import time
import tracemalloc
# Increase the limit for converting large integers to strings
sys.set_int_max_str_digits(0) # 0 means no limit
import fib_rs # This is our compiled Rust library
# --- Native Python Implementations ---
def fib_py_recursive(n):
if n <= 1:
return n
return fib_py_recursive(n - 1) + fib_py_recursive(n - 2)
def fib_py_iterative(n):
if n <= 1:
return n
a, b = 0, 1
for _ in range(2, n + 1):
a, b = b, a + b
return b
# --- Benchmarking Utilities ---
def measure_performance(func, arg, label):
# Measure Memory
tracemalloc.start()
start_time = time.perf_counter()
result = func(arg)
end_time = time.perf_counter()
current, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
duration = end_time - start_time
memory_mb = peak / 10**6
print(f"[{label}]")
# For very large numbers, show digit count instead of the full result
result_str = str(result) if result < 10**100 else f"<{len(str(result))} digits>"
print(f" Result : {result_str}")
print(f" Time : {duration:.6f} seconds")
print(f" Memory : {memory_mb:.6f} MB peak")
print("-" * 40)
return duration
# --- Main Execution ---
if __name__ == "__main__":
N_RECURSIVE = 35 # Don't go too high for Python recursion (e.g. >40 is very slow)
N_ITERATIVE = 100_000 # Large number to test iterative speed
print(f"=== RECURSIVE BENCHMARK (n={N_RECURSIVE}) ===")
print("Calculating...")
t_py = measure_performance(fib_py_recursive, N_RECURSIVE, "Python Native (Recursive)")
t_rs = measure_performance(fib_rs.fib_recursive, N_RECURSIVE, "Rust Pyo3 (Recursive)")
print(f"🚀 Speedup: Rust is {t_py / t_rs:.2f}x faster than Python\n")
print(f"=== ITERATIVE BENCHMARK (n={N_ITERATIVE}) ===")
t_py_iter = measure_performance(fib_py_iterative, N_ITERATIVE, "Python Native (Iterative)")
t_rs_iter = measure_performance(fib_rs.fib_iterative, N_ITERATIVE, "Rust Pyo3 (Iterative)")