Benchmarking Go Programs
Start with Benchmarking Go Programs
In this lesson, explore benchmarking go programs through one small Go program, and connect its output to the language rules behind it.
What you’ll learn
- Explain the main purpose of benchmarking go programs.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Benchmark functions start with BenchmarkXxx(b *testing.B) and run a loop controlled by b.N in a _test.go file. The test runner chooses repetitions to collect timings.
Benchmarks should do representative work, avoid accidentally optimized-away results, and report allocations when useful with -benchmem.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Tools, syntax and practical notes
sum_test.go
package main
import "testing"
var benchmarkResult int
func BenchmarkSum(b *testing.B) {
values := []int{1,2,3,4}
for i := 0; i < b.N; i++ { benchmarkResult = sum(values) }
}Run go test -run '^$' -bench BenchmarkSum -benchmem.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
func sum(values []int) int {
total := 0
for _, n := range values {
total += n
}
return total
}
func main() { fmt.Println("Sum:", sum([]int{1, 2, 3, 4})) }
Output
Sum: 10Trace what the program does
The small sum function has a predictable result. A benchmark can call it repeatedly under the testing package without hard-coding a wall-clock result.
Avoid common mistakes
- Never present a benchmark time as a universal constant.
- Printing within a benchmark loop usually measures I/O rather than the intended operation.
Try it yourself
Benchmark sum on a 100-element slice and compare -benchmem with a different algorithm.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Benchmarking Go Programs in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.