Benchmark

class rayne.benchmark.Benchmark(name: str | None = None, runs: int = 1000)

Create and run a microbenchmark.

Use this class as a context manager. Create the Benchmark and set the user code to measure with set_user_code(). Rayne automatically measures and reports the user code execution time when the context manager exits.

with Benchmark() as benchmark:
    benchmark.set_user_code(fibonacci, n=10)
name

Rayne assigns a name to each Benchmark. Rayne uses the name in the output to differentiate multiple benchmarks within a single benchmarking script. The default name is the string representation of the user code.

>>> with Benchmark() as benchmark:
>>>     benchmark.set_user_code(fibonacci, n=10)
>>> print(benchmark.name)
fibonacci

You can assign a custom name to the Benchmark.

>>> with Benchmark(name="Recursive") as benchmark:
>>>     benchmark.set_user_code(fibonacci, n=10)
>>> print(benchmark.name)
Recursive
>>> with Benchmark() as benchmark:
>>>     benchmark.name = "Recursive"
>>>     benchmark.set_user_code(fibonacci, n=10)
>>> print(benchmark.name)
Recursive
runs

Rayne runs the user code several times to build a statistical model of the execution time. The runs attribute controls how many times Rayne runs the user code. You can modify this value before the Benchmark context manager exits. For example, to run the user code 2000 times:

with Benchmark(runs=2000) as benchmark:
    benchmark.subject = fibonacci
with Benchmark() as benchmark:
    benchmark.runs = 2000
    benchmark.subject = fibonacci
set_user_code(function, **kwargs)

Set the user code to benchmark.

Parameters:
  • function (Callable) – The benchmark measures the execution time of this function.

  • kwargs – The benchmark passes these arguments to function.