Skip to content
Latchkey

go test -bench: Benchmarks in CI

go test -bench=<regex> runs benchmark functions and reports nanoseconds per operation; -benchmem adds allocation counts.

Benchmarks live alongside tests as func BenchmarkX(b *testing.B). In CI they catch performance regressions, often compared with benchstat across runs.

What it does

go test -bench takes a regex of benchmark names to run. By default go test does not run benchmarks, so you also pass -run ^$ to skip normal tests. -benchmem prints B/op and allocs/op; -benchtime controls how long each benchmark runs.

Common usage

Terminal
go test -bench=. -run '^$' -benchmem ./...
go test -bench=BenchmarkEncode -benchtime=5s ./pkg/codec
go test -bench=. -count=10 ./... | tee new.txt   # for benchstat

Flags

FlagWhat it does
-bench <regex>Run benchmarks matching the regex
-benchmemReport memory allocations per operation
-benchtime <dur|Nx>Run each benchmark for a duration or N iterations
-run '^$'Skip regular tests so only benchmarks run
-count <n>Repeat benchmarks n times for stable stats
-cpu <list>Run with the given GOMAXPROCS values

In CI

Benchmark numbers are noisy on shared runners, so pin them to a stable instance and use -count plus benchstat to compare old vs new rather than asserting absolute timings. Cache the build and module caches as usual. Keep benchmarks behind -run ^$ so they do not run in the normal test job.

Common errors in CI

"testing: warning: no tests to run" alongside benchmark output is expected when you pass -run ^$. If benchmarks never run, the -bench regex matched nothing; check the function name and that it starts with Benchmark. "b.N too small" style instability means -benchtime is too short for the runner; raise it.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →