Writing Benchmarks with testing.B
BenchmarkXxx, b.N loop, and -bench flag
Benchmark function signature
Benchmarks start with Benchmark and take *testing.B. They run in the _test.go file alongside regular tests.
func BenchmarkAdd(b *testing.B) {
for i := 0; i < b.N; i++ {
Add(2, 3)
}
}b.N
The testing framework automatically adjusts b.N — the number of loop iterations — until the benchmark runs for at least 1 second, producing a stable nanoseconds-per-operation figure.
All lessons in this course
- Writing Benchmarks with testing.B
- CPU Profiling with pprof
- Heap and Allocation Profiling
- Execution Tracing