Created
May 29, 2023 18:51
-
-
Save isaacharrisholt/8a9744f06ac27ac8cd95486f7634bfa7 to your computer and use it in GitHub Desktop.
Fibonacci - Python vs Rust benchmark
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 sys | |
from timeit import timeit | |
import fibbers | |
RUNS = 100 | |
def fibonacci(n: int) -> int: | |
if n <= 1: | |
return n | |
return fibonacci(n - 1) + fibonacci(n - 2) | |
def main(): | |
n = int(sys.argv[1]) | |
print(f"{fibonacci(n) = }") | |
print(f"{fibbers.fib(n) = }") | |
python_time_per_call = timeit(lambda: fibonacci(n), number=RUNS) / RUNS | |
print(f"\nPython μs per call: {python_time_per_call * 1_000_000:.2f} μs") | |
print(f"Python ms per call: {python_time_per_call * 1_000:.2f} ms") | |
rust_time_per_call = timeit(lambda: fibbers.fib(n), number=RUNS) / RUNS | |
print(f"\nRust μs per call: {rust_time_per_call * 1_000_000:.2f} μs") | |
print(f"Rust ms per call: {rust_time_per_call * 1_000:.2f} ms") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment