-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfib_bench.py
More file actions
192 lines (150 loc) · 5.92 KB
/
fib_bench.py
File metadata and controls
192 lines (150 loc) · 5.92 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
#!/usr/bin/env python3
"""Benchmark different Fibonacci implementations and plot timings.
Methods:
1. naive recursive
2. recursive with memoization (top-down DP)
3. bottom-up array (iterative DP)
4. matrix exponentiation (O(log n))
Usage: python fib_bench.py N1 N2 N3 ... [--repeat R] [--output out.png]
Notes:
- Naive recursion grows exponentially; by default it's skipped for n > 35 unless --allow-slow is set.
- Times are averaged over --repeat runs (default 3) for faster methods; naive uses 1 run by default.
"""
from __future__ import annotations
import argparse
import math
import time
from typing import Callable, Dict, List, Optional
import matplotlib.pyplot as plt
import numpy as np
def fib_recursive(n: int) -> int:
if n < 2:
return n
return fib_recursive(n - 1) + fib_recursive(n - 2)
def fib_memo(n: int, memo: Optional[Dict[int, int]] = None) -> int:
if memo is None:
memo = {}
if n < 2:
return n
if n in memo:
return memo[n]
memo[n] = fib_memo(n - 1, memo) + fib_memo(n - 2, memo)
return memo[n]
def fib_bottom_up(n: int) -> int:
if n < 2:
return n
a, b = 0, 1
for _ in range(2, n + 1):
a, b = b, a + b
return b
def mat_mult(A: List[List[int]], B: List[List[int]]) -> List[List[int]]:
return [
[A[0][0] * B[0][0] + A[0][1] * B[1][0], A[0][0] * B[0][1] + A[0][1] * B[1][1]],
[A[1][0] * B[0][0] + A[1][1] * B[1][0], A[1][0] * B[0][1] + A[1][1] * B[1][1]],
]
def mat_pow(mat: List[List[int]], n: int) -> List[List[int]]:
# Exponentiation by squaring
result = [[1, 0], [0, 1]]
base = mat
while n > 0:
if n & 1:
result = mat_mult(result, base)
base = mat_mult(base, base)
n >>= 1
return result
def fib_matrix(n: int) -> int:
# Using matrix [[1,1],[1,0]]^n gives F_{n+1} and F_n
if n < 2:
return n
M = [[1, 1], [1, 0]]
Mn = mat_pow(M, n - 1)
# Mn * [F1, F0] = [F_n, F_{n-1}] where [F1, F0] = [1, 0]
return Mn[0][0]
def time_function(fn: Callable[[int], int], n: int, repeat: int = 1) -> float:
# Run fn(n) repeat times and return average elapsed seconds
# For functions that may mutate shared state (memo), caller must handle it
times = []
for _ in range(repeat):
t0 = time.perf_counter()
fn(n)
t1 = time.perf_counter()
times.append(t1 - t0)
return float(sum(times) / len(times))
def benchmark(ns: List[int], repeat: int = 3, max_recursion_n: int = 35, allow_slow: bool = False):
methods = [
("naive_recursive", lambda n: fib_recursive(n)),
("memo_recursive", lambda n: fib_memo(n)),
("bottom_up", lambda n: fib_bottom_up(n)),
("matrix_pow", lambda n: fib_matrix(n)),
]
results: Dict[str, List[float]] = {name: [] for name, _ in methods}
for n in ns:
for name, fn in methods:
if name == "naive_recursive" and (n > max_recursion_n and not allow_slow):
results[name].append(float('nan'))
continue
# For memo_recursive, ensure a fresh memo per call
if name == "memo_recursive":
wrapped = lambda x, f=fn: f(x)
else:
wrapped = fn
this_repeat = 1 if name == "naive_recursive" else repeat
try:
t = time_function(wrapped, n, repeat=this_repeat)
except RecursionError:
t = float('nan')
results[name].append(t)
return results
def plot_results(ns: List[int], results: Dict[str, List[float]], out_path: str):
# prefer a clean style if available; fall back to default
try:
plt.style.use('seaborn-darkgrid')
except Exception:
try:
plt.style.use('ggplot')
except Exception:
pass
fig, ax = plt.subplots(figsize=(10, 6))
names_map = {
'naive_recursive': 'Naive Rec (exp)',
'memo_recursive': 'Memoized Rec (DP)',
'bottom_up': 'Bottom-up (array)',
'matrix_pow': 'Matrix pow (log n)'
}
for name, times in results.items():
y = np.array(times, dtype=np.float64)
ax.plot(ns, y, marker='o', label=names_map.get(name, name))
ax.set_xlabel('n')
ax.set_ylabel('Time (seconds)')
ax.set_title('Fibonacci: time comparison of methods')
ax.legend()
ax.set_xticks(ns)
# If range is wide, use log scale for y to show trends
finite = np.isfinite(np.array([t for vals in results.values() for t in vals], dtype=np.float64))
if finite.any():
times_all = np.array([t for vals in results.values() for t in vals], dtype=np.float64)
times_all = times_all[np.isfinite(times_all)]
if times_all.max() / max(times_all.min(), 1e-12) > 1000:
ax.set_yscale('log')
plt.tight_layout()
plt.savefig(out_path)
print(f"Saved plot to: {out_path}")
def parse_args():
p = argparse.ArgumentParser(description='Benchmark Fibonacci implementations')
p.add_argument('ns', metavar='N', type=int, nargs='+', help='n values to benchmark')
p.add_argument('--repeat', '-r', type=int, default=3, help='repeat runs for averaging (except naive which defaults to 1)')
p.add_argument('--output', '-o', default='fib_bench.png', help='output plot filename')
p.add_argument('--max-recursive', type=int, default=35, help='max n for naive recursion (skipped above this unless --allow-slow)')
p.add_argument('--allow-slow', action='store_true', help='allow running naive recursion for large n (may take very long)')
return p.parse_args()
def main():
args = parse_args()
ns = sorted(set(args.ns))
print(f"Benchmarking n values: {ns}")
results = benchmark(ns, repeat=args.repeat, max_recursion_n=args.max_recursive, allow_slow=args.allow_slow)
print("Results (seconds):")
for name, times in results.items():
print(f" {name}: {times}")
plot_results(ns, results, args.output)
if __name__ == '__main__':
main()