Sub-benchmark
- Go course
- Intermediate
- Lesson 50/80
- 4 min
Learn to run sub-benchmarks with b.Run.
Sub-benchmarks
With b.Run you can measure different input sizes under one benchmark; growth behavior (linear or quadratic) shows up this way:
func BenchmarkAra(b *testing.B) {
for _, n := range []int{10, 1000, 100000} {
veri := sirali(n)
b.Run(fmt.Sprintf("n=%d", n), func(b *testing.B) {
for i := 0; i < b.N; i++ {
sinkBool = ikiliAra(veri, n/2)
}
})
}
}Output: BenchmarkAra/n=10, BenchmarkAra/n=1000... -bench=Ara/n=1000 runs a single sub-measurement.
Prepare data outside
Preparing a sub-benchmark's input before calling b.Run keeps the setup time out of the measurement; each sub-benchmark starts with its own timer. The closure passed to b.Run safely captures the loop variable (n, new on every iteration since Go 1.22).
Practice Measuring by size
Let topla(n int) int sum 1 to n in a loop. Measure the sizes []int{10, 1000} with testing.Benchmark and print whether the large size's time per operation (NsPerOp()) is greater than the small one's.
Starter code
package main
import (
"fmt"
"testing"
)
func main() {
// buraya yaz
}Sample solution
package main
import (
"fmt"
"testing"
)
var sink int
func topla(n int) int {
t := 0
for i := 1; i <= n; i++ {
t += i
}
return t
}
func main() {
var sure []int64
for _, n := range []int{10, 1000} {
r := testing.Benchmark(func(b *testing.B) {
for i := 0; i < b.N; i++ {
sink = topla(n)
}
})
sure = append(sure, r.NsPerOp())
}
fmt.Println(sure[1] > sure[0])
}Expected output
true
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 If ns/op also grows about 100× when n grows 100×, what is the algorithm like?
- Linear (O(n)) Correct answer
- Logarithmic (O(log n))
- Constant (O(1))
- Quadratic (O(n²))
Explanation: If time grows at the same rate as the input it is linear; quadratic would grow 10,000×, logarithmic only a little.
2 Sub-benchmark
b.____(fmt.Sprintf("n=%d", n), func(b *testing.B) {
// ...
})
b.Run(fmt.Sprintf("n=%d", n), func(b *testing.B) {
// ...
})
Explanation: b.Run starts a sub-benchmark with the given name.
3 Complexity and growth (n×100)
| Term | Meaning |
|---|---|
O(1) |
Unchanged |
O(log n) |
~3× |
O(n) |
~100× |
O(n²) |
~10,000× |