From 3858349ec956b4abb052ba3191da16dc487c4ad4 Mon Sep 17 00:00:00 2001 From: Meir Fischer Date: Sun, 25 Jun 2017 21:17:52 -0400 Subject: [PATCH] testing: always ReadMemStats before first benchmark run If the only way the user indicates they want alloc stats shown is via ReportAllocs, we don't know that until benchFunc is run. Therefore, StopTimer's ReadMemStats will return incorrect data for single cycle runs since there's no counterpart ReadMemStats from StartTimer that initializes alloc stats. It appears that this bug was introduced by CL 46612, "testing: only call ReadMemStats if necessary when benchmarking" Fixes #20590 Change-Id: I3b5ef91677823f4b98011880a3be15423baf7e33 Reviewed-on: https://go-review.googlesource.com/46612 Reviewed-by: Brad Fitzpatrick Run-TryBot: Brad Fitzpatrick TryBot-Result: Gobot Gobot --- src/testing/benchmark.go | 8 +++----- src/testing/sub_test.go | 10 ++++++++++ 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/src/testing/benchmark.go b/src/testing/benchmark.go index 8b7f5cebaf..be9e96d50c 100644 --- a/src/testing/benchmark.go +++ b/src/testing/benchmark.go @@ -73,11 +73,9 @@ type B struct { // a call to StopTimer. func (b *B) StartTimer() { if !b.timerOn { - if *benchmarkMemory || b.showAllocResult { - runtime.ReadMemStats(&memStats) - b.startAllocs = memStats.Mallocs - b.startBytes = memStats.TotalAlloc - } + runtime.ReadMemStats(&memStats) + b.startAllocs = memStats.Mallocs + b.startBytes = memStats.TotalAlloc b.start = time.Now() b.timerOn = true } diff --git a/src/testing/sub_test.go b/src/testing/sub_test.go index af2d39c5be..acf5dea878 100644 --- a/src/testing/sub_test.go +++ b/src/testing/sub_test.go @@ -540,6 +540,16 @@ func TestBenchmarkStartsFrom1(t *T) { }) } +func TestBenchmarkReadMemStatsBeforeFirstRun(t *T) { + var first = true + Benchmark(func(b *B) { + if first && (b.startAllocs == 0 || b.startBytes == 0) { + panic(fmt.Sprintf("ReadMemStats not called before first run")) + } + first = false + }) +} + func TestParallelSub(t *T) { c := make(chan int) block := make(chan int) -- 2.50.0