Last active
June 25, 2025 14:08
-
-
Save neeyatlotlikar/5b5bc0599daea1f8771bb6d286937711 to your computer and use it in GitHub Desktop.
This Python script benchmarks the performance difference between two recursive implementations of the Fibonacci sequence: slow_fib(n): a naive recursive function (beautifully slow). fib(n): an optimized version using functools.lru_cache for memoization (blazing fast after the first call).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
from functools import lru_cache | |
@lru_cache(maxsize=None) | |
def fib(n: int) -> int: | |
if n < 2: | |
return n | |
return fib(n - 1) + fib(n - 2) | |
def slow_fib(n: int) -> int: | |
if n < 2: | |
return n | |
return slow_fib(n - 1) + slow_fib(n - 2) | |
if __name__ == "__main__": | |
n = 40 | |
print(f"Calculating Fibonacci of {n} without memoization:") | |
start_time = time.time() | |
print(slow_fib(n)) | |
end_time = time.time() | |
print(f"Function slow_fib took {end_time - start_time:.4f} seconds") | |
print() | |
print(f"Calculating Fibonacci of {n} using memoization:") | |
start_time = time.time() | |
fib.cache_clear() # Clear cache before measuring | |
print(fib(n)) | |
end_time = time.time() | |
print(f"Function fib took {end_time - start_time:.4f} seconds") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: