0PricingLogin
Go Academy · Lesson

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

  1. Writing Benchmarks with testing.B
  2. CPU Profiling with pprof
  3. Heap and Allocation Profiling
  4. Execution Tracing
← Back to Go Academy