From 396b153ec454cd427f97be4d994a903e2c4b244f Mon Sep 17 00:00:00 2001 From: hopehook Date: Sat, 30 Jul 2022 12:47:51 +0800 Subject: [PATCH] testing: add Elapsed method to testing.B Elapsed returns the measured elapsed time of the benchmark, but does not change the running state of the timer. Fixes #43620. Change-Id: Idd9f64c4632518eec759d2ffccbf0050d84fcc03 Reviewed-on: https://go-review.googlesource.com/c/go/+/420254 Reviewed-by: Dmitri Shuralyov TryBot-Result: Gopher Robot Auto-Submit: Bryan Mills Reviewed-by: Dmitri Shuralyov Run-TryBot: hopehook Reviewed-by: Bryan Mills --- api/next/43620.txt | 1 + src/testing/benchmark.go | 11 +++++++++++ src/testing/benchmark_test.go | 3 +++ 3 files changed, 15 insertions(+) create mode 100644 api/next/43620.txt diff --git a/api/next/43620.txt b/api/next/43620.txt new file mode 100644 index 0000000000..9d272fd0c7 --- /dev/null +++ b/api/next/43620.txt @@ -0,0 +1 @@ +pkg testing, method (*B) Elapsed() time.Duration #43620 \ No newline at end of file diff --git a/src/testing/benchmark.go b/src/testing/benchmark.go index 4fee421d39..ce1ab6da37 100644 --- a/src/testing/benchmark.go +++ b/src/testing/benchmark.go @@ -337,6 +337,17 @@ func (b *B) launch() { b.result = BenchmarkResult{b.N, b.duration, b.bytes, b.netAllocs, b.netBytes, b.extra} } +// Elapsed returns the measured elapsed time of the benchmark. +// The duration reported by Elapsed matches the one measured by +// StartTimer, StopTimer, and ResetTimer. +func (b *B) Elapsed() time.Duration { + d := b.duration + if b.timerOn { + d += time.Since(b.start) + } + return d +} + // ReportMetric adds "n unit" to the reported benchmark results. // If the metric is per-iteration, the caller should divide by b.N, // and by convention units should end in "/op". diff --git a/src/testing/benchmark_test.go b/src/testing/benchmark_test.go index 3b1dc8275b..7e456f9a40 100644 --- a/src/testing/benchmark_test.go +++ b/src/testing/benchmark_test.go @@ -176,5 +176,8 @@ func ExampleB_ReportMetric() { // This metric is per-operation, so divide by b.N and // report it as a "/op" unit. b.ReportMetric(float64(compares)/float64(b.N), "compares/op") + // This metric is per-time, so divide by b.Elapsed and + // report it as a "/ns" unit. + b.ReportMetric(float64(compares)/float64(b.Elapsed().Nanoseconds()), "compares/ns") }) } -- 2.50.0