Below is a self-contained script that implements both the recursive and iterative factorial functions, and then benchmarks them using Python’s time module. You can tweak N, the number you’re taking the factorial of, and CALLS (how many times to call each version) to see how the timings change.
import time
import statistics
import sys
# (1) Increase recursion limit if you plan to benchmark large n
sys.setrecursionlimit(2000)
# (2) Factorial implementations
def factorial_recursive(n):
if n < 0:
raise ValueError("Factorial is not defined for negative numbers.")
if n == 0 or n == 1:
return 1
return n * factorial_recursive(n - 1)
def factorial_iterative(n):
if n < 0:
raise ValueError("Factorial is not defined for negative numbers.")
result = 1
for i in range(2, n + 1):
result *= i
return result
# (3) Benchmark helper
def benchmark(func, n, calls=10000, repeats=5):
"""
Runs func(n) `calls` times, repeats that measurement `repeats` times,
and returns a list of elapsed times.
"""
times = []
for _ in range(repeats):
start = time.perf_counter()
for __ in range(calls):
func(n)
end = time.perf_counter()
times.append(end - start)
return times
# (4) Run benchmarks
if __name__ == "__main__":
N = 300 # the value to compute factorial of
CALLS = 20000 # how many times to run each version per repeat
REPEATS = 5 # how many repeats to take
print(f"Benchmarking factorial({N}) with {CALLS} calls × {REPEATS} repeats\n")
# Recursive
rec_times = benchmark(factorial_recursive, N, calls=CALLS, repeats=REPEATS)
print("Recursive:",
f"min={min(rec_times):.4f}s",
f"median={statistics.median(rec_times):.4f}s",
f"max={max(rec_times):.4f}s")
# Iterative
iter_times = benchmark(factorial_iterative, N, calls=CALLS, repeats=REPEATS)
print("Iterative:",
f"min={min(iter_times):.4f}s",
f"median={statistics.median(iter_times):.4f}s",
f"max={max(iter_times):.4f}s")
How it works:
- We bump the recursion limit so that
factorial_recursive(300) doesn’t blow the stack.
- We define both versions of
factorial.
- The
benchmark() helper runs a given function calls times, measures elapsed wall-clock time, and does that repeats times.
- We print the min/median/max over those repeats for easy comparison.
Feel free to adjust N, CALLS and REPEATS to suit your use case! 😃