Internals
High-level notes for maintainers and curious users.
Core components
Section titled “Core components”- Bench / bench decorator
Bench
holdsCase
items;Bench(...).bench(...)
registers decorated functions.bench(**opts)
is a shorthand for the global default suite.
- Case
- Metadata:
name
,mode
(“func” or “context”),n
,repeat
,warmup
,args/kwargs
,params
,group
,baseline
. params
→ cartesian product variants via_make_variants
.
- Metadata:
- BenchContext
- Manual timing:
start()/end()
accumulates nanoseconds; excludes setup noise.
- Manual timing:
- Result
- Aggregates per-call times (
per_call_ns
) and computes stats:mean
,median
,stdev
,min
,max
,p(q)
.
- Aggregates per-call times (
Discovery and execution (CLI)
Section titled “Discovery and execution (CLI)”discover(paths)
: files or**/*bench.py
under directories.load_module_from_path
: import file with a stable module name (_module_name_for_path
).run(...)
pipeline:- Optional warmup per case.
_prepare_variants
: detectsBenchContext
usage and calibratesn
per variant using--budget
/--max-n
(or “smoke”).- Execute repeats via
_run_single_repeat
and collectResult
s. - Filter, sort, and render table.
Calibration
Section titled “Calibration”_calibrate_n(...)
growsn
exponentially towardtarget_ns
and refines with ±20% probes.- Context mode:
- If
BenchContext
is actually used (detected by a probe call), only the hot region is timed. - Otherwise, the whole function is timed (same as function mode).
- If
Accuracy & robustness
Section titled “Accuracy & robustness”- Clock:
perf_counter_ns
when available. - GC: collect and disable around runs; CLI attempts
gc.freeze()
if present. - Warmup: executes untimed iterations to stabilize caches/CPU.
- Percentiles: linear interpolation.
- Colors: TTY-detected, opt-out with
--no-color
.
Table & baseline
Section titled “Table & baseline”- Groups are rendered with a dim header.
- Baseline chosen by
baseline=True
or name heuristic (contains “baseline”/“base”). vs base
shows≈ same
when relative mean diff ≤ 1%.
Possible extensions
Section titled “Possible extensions”- Parallel workers for independent variants.
- JSON/CSV export.
- Regression compare against previous runs.
- Setup/teardown hooks per case.