0Pricing
Go Academy · Lesson

Writing Benchmarks with testing.B

BenchmarkXxx, b.N loop, and -bench flag

Writing Benchmarks with testing.B is a free Go Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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.

Running benchmarks

Benchmarks do not run with go test alone. Use -bench to enable them:

go test -bench=. -benchmem ./...
// BenchmarkAdd-8  500000000  2.13 ns/op  0 B/op  0 allocs/op

-benchmem flag

-benchmem adds allocation stats: bytes per operation and number of allocations per operation. High allocations often indicate performance problems.

b.ResetTimer

Call b.ResetTimer() after expensive setup that should not be counted in the benchmark:

func BenchmarkQuery(b *testing.B) {
    db := setupDB() // expensive
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        db.Query("SELECT 1")
    }
}

b.StopTimer / b.StartTimer

Pause and resume the timer around setup/teardown that should not count toward the benchmark time.

for i := 0; i < b.N; i++ {
    b.StopTimer()
    data := generateInput()
    b.StartTimer()
    process(data)
}

b.SetBytes

Call b.SetBytes(n) to report throughput (bytes/sec) in addition to time/op. Useful for benchmarking serialisation or network code.

b.SetBytes(int64(len(payload)))
for i := 0; i < b.N; i++ {
    encode(payload)
}

Comparing benchmarks

Use benchstat to compare two benchmark runs and see statistically significant differences:

go test -bench=. -count=10 > before.txt
# make change
go test -bench=. -count=10 > after.txt
benchstat before.txt after.txt

Preventing dead-code elimination

Assign the result to a package-level variable or sink to prevent the compiler from optimising away the benchmarked code:

var result int
func BenchmarkFib(b *testing.B) {
    for i := 0; i < b.N; i++ {
        result = Fib(20)
    }
}

Sub-benchmarks

Use b.Run to create named sub-benchmarks, similar to table-driven tests:

for _, size := range []int{10, 100, 1000} {
    b.Run(fmt.Sprintf("size=%d", size), func(b *testing.B) {
        for i := 0; i < b.N; i++ { sort(make([]int, size)) }
    })
}

Benchmark vs profiling

Benchmarks quantify performance. Profiling (pprof) shows where time is spent. Use benchmarks to measure; use profiling to diagnose where to optimise.

Quick Check

Why must the benchmark loop body use the result to prevent compiler optimisation?

Recap: Benchmarks

Key points:

  • BenchmarkXxx(b *testing.B) with for i := 0; i < b.N; i++
  • go test -bench=. -benchmem for allocation stats
  • b.ResetTimer() after expensive setup
  • Use benchstat to compare runs; assign results to prevent elimination

Frequently asked questions

Is the “Writing Benchmarks with testing.B” lesson free?

Yes — the full text of “Writing Benchmarks with testing.B” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.

What will I learn in “Writing Benchmarks with testing.B”?

BenchmarkXxx, b.N loop, and -bench flag You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Go Academy?

No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Writing Benchmarks with testing.B” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Go Academy lesson?

Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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