Getting Started¶
Note
The commands in this tutorial are for Python 3 on Linux. For other platforms, adjust the commands accordingly. Rayne should work on any platform.
Install Rayne¶
Start by installing Rayne from PyPI. Add it to your requirements or pyproject file, or install it manually with
pip3 install rayne
Write Your Code¶
For this tutorial, we’ll benchmark two Fibonacci implementations: a recursive function and the closed form equation. [1]
The full code for this example is in the repository.
Rayne requires that you encapsulate your code in a Callable object.
1def closed_form(n: int) -> int:
2 """Calculate F(n) using the closed form equation."""
3 phi = (1 + sqrt(5)) / 2
4 psi = (1 - sqrt(5)) / 2
5 return int((phi**n - psi**n) / sqrt(5))
6
7
8def recursive(n: int) -> int:
9 """Calculate F(n) using recursion."""
10 if n <= 0:
11 return 0
12 if n == 1:
Write Your Benchmarks¶
Rayne is designed as a context manager.
Instantiate a Benchmark object, set the code to execute, and exit the context manager.
When the context manager exits, Rayne runs your code and measures the run time.
1from rayne import Benchmark
2
3
4
5if __name__ == "__main__":
6 with Benchmark() as benchmark:
7 benchmark.set_user_code(closed_form, n=5)
8
9 with Benchmark() as benchmark:
10 benchmark.set_user_code(recursive, n=5)
Run Your Benchmarks¶
Run the benchmark script with Python. By default, Rayne runs your code 1000 times. Rayne prints the average run time in nanoseconds.
$ python3 fibonacci.py
closed_form: 1578 ns
recursive: 1956 ns
Next Steps¶
Read the
Benchmarkreference documentation