Module 9 · Lesson 3 of 543/50 in the course~12 min
Module lessons (3/5)
Benchmarks and profiles
Lesson preview5 hands-on exercises readyCourse Go · Module 9 — Testing, modules and tooling
Functions BenchmarkXxx(b *testing.B), the loop for i := 0; i < b.N; i++, go test -bench=..
What you'll learn in this lesson
- Write valid benchmarks with signature
func BenchmarkXxx(b *testing.B)and loop throughb.N. - Exclude preparation times from the count using
b.ResetTimer()orb.StopTimer()/b.StartTimer(). - Measure bytes and allocations per operation with
b.ReportAllocs()and-benchmem. - Prevent the compiler from eliminating dead code by assigning the result to a package variable
sink.
Overview
In addition to functional correctness, Go integrates in the same go test command a statistical engine to measure CPU time and pressure on the garbage collector via BenchmarkXxx(b *testing.B) functions.
The runner runs the benchmark by progressively adjusting b.N (1, 100, 10,000…) until a statistically stable measurement is obtained:
Sections covered in this lesson
- 1Basic structure and parameter
b.N - 2Execution commands and metrics
- 3Exclude expensive setups with
b.ResetTimerandb.Run - 4Dead-Code Elimination Trap
- 5Guided practice
- 6Check for understanding
Pro Lesson · Module 9 — Testing, modules and tooling
Unlock "Benchmarks and profiles" and the full Course Go curriculum
Functions `BenchmarkXxx(b *testing.B)`, the loop `for i := 0; i < b.N; i++`, `go test -bench=.`.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Course Go plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.