Go Academy · Lesson

Writing Benchmarks with testing.B

BenchmarkXxx, b.N loop, and -bench flag

Lesson 1 of 413 steps

Writing Benchmarks with testing.B is a free Go Academy lesson on CoddyKit. This is lesson 1 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, and your progress syncs across the web and the CoddyKit app. The Go Academy course includes 4 lessons in total.

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
Free to start

Learn Go with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
51
Lessons
203

Frequently Asked Questions

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

Yes — any 3 lessons of the Go Academy learning path, including “Writing Benchmarks with testing.B”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Go Academy course includes 4 lessons in total.

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, so you can start here or from the beginning and move at your own pace. This is lesson 1 of 4.

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