Skip to content

Commit

Permalink
testing: don't measure cleanup time after B.Loop
Browse files Browse the repository at this point in the history
B.Loop resets the timer on the first iteration so that setup code
isn't measured, but it currently leaves the timer running after the
last iteration, meaning that cleanup code will still be measured. Fix
this by stopping the timer when B.Loop returns false to indicate the
end of the benchmark.

Updates #61515

Change-Id: I0e0502cb2ce3c24cf872682b88d74e8be2c4529b
Reviewed-on: https://go-review.googlesource.com/c/go/+/635898
Reviewed-by: Junyang Shao <[email protected]>
Auto-Submit: Austin Clements <[email protected]>
LUCI-TryBot-Result: Go LUCI <[email protected]>
Reviewed-by: Cherry Mui <[email protected]>
  • Loading branch information
aclements authored and gopherbot committed Dec 16, 2024
1 parent c1f2542 commit 18b5435
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/testing/benchmark.go
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,8 @@ func (b *B) ReportMetric(n float64, unit string) {
func (b *B) stopOrScaleBLoop() bool {
timeElapsed := highPrecisionTimeSince(b.start)
if timeElapsed >= b.benchTime.d {
// Stop the timer so we don't count cleanup time
b.StopTimer()
return false
}
// Loop scaling
Expand Down Expand Up @@ -393,6 +395,7 @@ func (b *B) loopSlowPath() bool {
b.loopN++
return true
}
b.StopTimer()
return false
}
// Handles fixed time case
Expand All @@ -413,7 +416,8 @@ func (b *B) loopSlowPath() bool {
//
// Loop resets the benchmark timer the first time it is called in a benchmark,
// so any setup performed prior to starting the benchmark loop does not count
// toward the benchmark measurement.
// toward the benchmark measurement. Likewise, when it returns false, it stops
// the timer so cleanup code is not measured.
//
// The compiler never optimizes away calls to functions within the body of a
// "for b.Loop() { ... }" loop. This prevents surprises that can otherwise occur
Expand Down
6 changes: 6 additions & 0 deletions src/testing/loop_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ func TestBenchmarkBLoop(t *T) {
var initialStart highPrecisionTime
var firstStart highPrecisionTime
var lastStart highPrecisionTime
var runningEnd bool
runs := 0
iters := 0
finalBN := 0
Expand All @@ -22,6 +23,7 @@ func TestBenchmarkBLoop(t *T) {
iters++
}
finalBN = b.N
runningEnd = b.timerOn
})
// Verify that a b.Loop benchmark is invoked just once.
if runs != 1 {
Expand All @@ -46,6 +48,10 @@ func TestBenchmarkBLoop(t *T) {
if lastStart != firstStart {
t.Errorf("timer was reset during iteration")
}
// Verify that it stopped the timer after the last loop.
if runningEnd {
t.Errorf("timer was still running after last iteration")
}
}

// See also TestBenchmarkBLoop* in other files.

0 comments on commit 18b5435

Please sign in to comment.