Lesson 44 of 60 · Go
Writing Benchmarks – `testing.B`
Duration: 15 minutes
Benchmark Example
This lesson explains the main concept clearly with beginner-friendly examples and background so you can learn why the code works.
func BenchmarkEncodeJSON(b *testing.B) {
obj := map[string]int{"a":1,"b":2,"c":3}
for i := 0; i < b.N; i++ {
json.Marshal(obj)
}
}
Run with:
$ go test -bench=. -benchmem
The output shows ns/op, allocs/op, and B/op.
Controlling benchmark size
func BenchmarkMultiply(b *testing.B) {
for i := 0; i < b.N; i++ { multiply(12345, 6789) }
}
Use b.ResetTimer() after any preparatory work.