codspeed-write-benchmarks
Write Benchmarks
A benchmark is useful when a change in its result means a change in the code. Apply the rules below when writing a benchmark, and use them as the checklist when one misbehaves.
Run benchmarks through the CodSpeed CLI (codspeed run, codspeed exec) and read results with the CodSpeed MCP tools, not from raw framework output.
Rules
-
Relevance: One benchmark answers one question about a real hot path or user-facing operation. Use inputs with a realistic size and distribution.
-
Validity: The code under test must actually run. Use its result (return it, or pass it to the framework's black box) and keep inputs opaque to the optimizer, otherwise the work can be removed or computed at compile time. See optimized-out benchmarks.
-
Measured region: Measure only the operation under test. Build inputs outside the measured code. If the operation mutates its input, give every iteration a fresh copy through the framework's setup hook. Every iteration must do the same work.
-
Determinism: The same code must do the same work on every run. Seed random generators, use fixed-seed hashing or ordered containers, sort directory listings, and read committed fixtures. No network, clock, or environment-dependent branches. See Benchmark Variance.
-
State isolation: A result must not depend on which benchmarks ran before it. Avoid shared caches and globals. Allocator and garbage collector state carries over between benchmarks, so allocate inputs in setup rather than in the measured code. If a micro-benchmark still moves with unrelated code changes, build it into its own binary. See Reducing Variance.