b.ResetTimer
- Go course
- Intermediate
- Lesson 48/80
- 4 min
Learn b.ResetTimer to exclude setup time.
b.ResetTimer
If there is expensive setup before the measurement (building large data, reading a file), its time leaks into the result. b.ResetTimer() resets the elapsed time and allocations so far:
func BenchmarkSirala(b *testing.B) {
veri := rastgeleDilim(100_000) // shouldn't be measured
b.ResetTimer()
for i := 0; i < b.N; i++ {
kopya := slices.Clone(veri)
slices.Sort(kopya)
}
}Why did we sort a copy?
If the slice is sorted in the first iteration, later iterations work on already-sorted data and look much faster. Every iteration of a benchmark must do the same work, so a copy is sorted each time. The copying cost also enters the result; for a fair comparison this is usually accepted, or measured with a separate benchmark and subtracted.
Practice Measuring after setup
Inside testing.Benchmark, first prepare a 1000-element slice, call b.ResetTimer(), then compute the slice's sum in the loop and assign it to sink. Print whether sink equals 499500.
Starter code
package main
import (
"fmt"
"testing"
)
func main() {
// buraya yaz
}Sample solution
package main
import (
"fmt"
"testing"
)
var sink int
func main() {
testing.Benchmark(func(b *testing.B) {
veri := make([]int, 1000)
for i := range veri {
veri[i] = i
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
t := 0
for _, v := range veri {
t += v
}
sink = t
}
})
fmt.Println(sink == 499500)
}Expected output
true
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is used for work that must happen every iteration inside the loop but shouldn't be measured?
- b.Skip()
- time.Sleep
- b.StopTimer() and b.StartTimer() Correct answer
- b.ResetTimer() on every iteration
Explanation: StopTimer/StartTimer pause the measurement temporarily; but called too often, their own cost distorts the result.
2 Don't measure setup
veri := hazirla()
b.____()
for i := 0; i < b.N; i++ {
isle(veri)
}
veri := hazirla()
b.ResetTimer()
for i := 0; i < b.N; i++ {
isle(veri)
}
Explanation: ResetTimer removes the setup time from the measurement.
3 Timer method
| Term | Meaning |
|---|---|
ResetTimer |
Reset so far |
StopTimer |
Pause measuring |
StartTimer |
Resume measuring |
b.Loop() |
Go 1.24 automatic |