Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Benchmarks

A <Project>.Benchmarks project measures the hot paths of <Project> with BenchmarkDotNet, on inputs built in code. It needs no game data, so you can compare two versions of a function without rerunning a whole command.

ProjectMeasures
BookAtlas.Exporter.BenchmarksBookAtlas.Exporter

Running

nix develop --command dotnet run -c Release --project <Project>.Benchmarks -- --filter '*' --job short
OptionEffect
--filter '<pattern>'Runs the benchmarks whose full name matches, for example '*Landscape*'
--job dryOne iteration of each benchmark, to check that they run
--job short3 warmups and 3 iterations: enough to compare two versions
no --jobThe default job: longer, tighter error margins
no --filterAsks which benchmarks to run

BenchmarkDotNet refuses a Debug build: always pass -c Release. Results go to BenchmarkDotNet.Artifacts/, which git ignores.

Run on an idle machine. Another process on the cores, a running command for example, makes the Error column larger than the difference you look for. A benchmark that runs in parallel suffers most.

Reading the results

ColumnMeaning
MeanTime per operation
ErrorHalf of the 99.9% confidence interval: the true mean lies within Mean ± Error
StdDevSpread between iterations
AllocatedManaged memory allocated per operation

A difference between two versions is real when it is well above their Error. Allocations don’t vary between runs: a change in Allocated is real even when the time is too noisy to tell.

To compare a change, run the same filter before and after it, on the same machine.

In CI

The Benchmarks workflow (.forgejo/workflows/benchmarks.yaml) runs on every pull request that changes C# code. It runs every *.Benchmarks project of the pull request’s base and of its head in 5 rounds on the same runner, alternating the sides: base then head, head then base, and so on. It then posts the comparison as a comment on the pull request, and updates that comment on every later push.

A shared runner’s load comes in bursts that last longer than a benchmark. When the whole base runs before the whole head, a burst that hits one side shifts every benchmark of that side. A parallel benchmark can also settle in a slower mode for a whole process. With alternating rounds, either one hits one round of one side, and the other rounds disagree with it.

The comment lists the changed benchmarks first: faster, slower, new, removed, or with different allocations. Every benchmark follows in a collapsed section. Base and Head are the fastest round of each side, since load only adds time, and Change compares them. Rounds is the lowest and highest change between a base round and the head round run next to it.

ChangeMeaning
faster or slowerEvery round differs in that direction by more than the error margins of both runs
noiseAt least one round doesn’t
new or removedThe benchmark exists on one side only
failed on the base or failed on the headThe benchmark has no result in any round of that side
allocations changedThe allocations differ, whatever the time

Each round runs a job shorter than the default one, which aims at 500 ms an iteration and runs up to 100 iterations when the times are noisy. More iterations in a round don’t help against a burst that lasts the whole round; more rounds do.

tool/benchmark-rounds.sh runs the rounds, and tool/benchmark-report.sh builds the comment’s tables from their results. To reproduce the comparison locally, with the base checked out in a worktree:

git worktree add --detach ../base <base commit>
nix develop --command tool/benchmark-rounds.sh ../base . /tmp/benchmarks 5 \
  --iterationTime 250 --warmupCount 6 --iterationCount 10
tool/benchmark-report.sh /tmp/benchmarks/base /tmp/benchmarks/head

tool/benchmark-report.sh needs jq, which the dev shell doesn’t provide. It also reads two plain --exporters json result folders, each as one round.

A benchmark that runs in parallel needs iterations of 250 ms and 6 warmups: with iterations of 100 ms and 3 warmups, the thread pool is still settling while it is measured.

Limitations:

  • A load that lasts the whole run still slows both sides, and a real change smaller than the spread of the rounds shows as noise. Trust the allocations more than the times, and confirm a time on an idle machine.
  • Under the JIT, dynamic PGO profiles a parallel benchmark differently from one process to the next: a change that only moves code can make a scenario bimodal, two stable means a few percent apart. Before you treat such a gap as a regression, rerun both sides with --envVars DOTNET_TieredPGO:0 and time the Native AOT export, which has no dynamic PGO.
  • On a pull request from a fork, the workflow token can’t comment: the table is only in the job log.
  • A pull request that changes no .cs or .csproj file doesn’t run the workflow, and an older comment stays as it was.

Finding what to benchmark

A benchmark measures only the code you point it at. Profile a real run first to find where the time goes. dotnet-trace attaches to a running process without stopping it:

nix develop --command dotnet tool run dotnet-trace collect -p <pid> --duration 00:00:00:30 -o run.nettrace
nix develop --command dotnet tool run dotnet-trace report run.nettrace topN -n 25

Profile a Release build: in a Debug build, small methods aren’t inlined and take a share of the profile they don’t have in Release. Threads waiting in the thread pool (LowLevelLifoSemaphore.WaitForSignal) are idle, not lost time: check the cores the process uses with top.

Writing a benchmark

  • Mirror the folders of the measured project, as the tests do: a benchmark of BookAtlas.Exporter/Pipelines/Maps/Objects/ goes in Pipelines/Maps/Objects/.
  • Build the inputs in [GlobalSetup], from code. Use seeded random data where the content changes the cost, so every run measures the same input. Shared builders go in Support/.
  • End [GlobalSetup] with TieredJit.WarmUp, calling the benchmark method. BenchmarkDotNet’s pilot sizes the iterations from the first calls: on code the JIT hasn’t optimized yet, it picks iterations shorter than --iterationTime, which are noisier.
  • Call the method the project itself calls, not a copy of its loop.
  • Return the result, or a value derived from it, so the JIT doesn’t drop the work.
  • When one call processes many items (pixels, samples, records), set OperationsPerInvoke to their count: Mean is then the time per item.
  • Use [Params] for the variants worth comparing, such as a kernel or a size. Each value multiplies the run time.