]> Cypherpunks repositories - gostls13.git/commitdiff
testing: add an example showcasing B.RunParallel with B.ReportMetric
authorEddie Lopez <ejlopez00@gmail.com>
Fri, 30 Sep 2022 20:51:33 +0000 (16:51 -0400)
committerGopher Robot <gobot@golang.org>
Fri, 7 Oct 2022 17:49:17 +0000 (17:49 +0000)
This commit was dedicated to adding an example of using B.ReportMetrics
with B.RunParallel called ExampleB_ReportMetric_parallel. In this
example, the same algorithm for ExampleB_ReportMetric was used, instead
with a concurrent for loop using PB.Next instead of a standard one.
There is also notes noting when to use the B.ReportMetric methods when
running concurrent testing.

Fixes #50756
Change-Id: I2a621b4e367af5f4ec47d38a0da1035a8d52f628
Reviewed-on: https://go-review.googlesource.com/c/go/+/437815
Reviewed-by: Carlos Amedee <carlos@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: Bryan Mills <bcmills@google.com>
Reviewed-by: Bryan Mills <bcmills@google.com>
Auto-Submit: Bryan Mills <bcmills@google.com>

src/testing/benchmark_test.go

index 7e456f9a409e5784feaef19dc0feb0504bb5346d..2987170827920badac167251046e401884d93b05 100644 (file)
@@ -181,3 +181,33 @@ func ExampleB_ReportMetric() {
                b.ReportMetric(float64(compares)/float64(b.Elapsed().Nanoseconds()), "compares/ns")
        })
 }
+
+func ExampleB_ReportMetric_parallel() {
+       // This reports a custom benchmark metric relevant to a
+       // specific algorithm (in this case, sorting) in parallel.
+       testing.Benchmark(func(b *testing.B) {
+               var compares atomic.Int64
+               b.RunParallel(func(pb *testing.PB) {
+                       for pb.Next() {
+                               s := []int{5, 4, 3, 2, 1}
+                               sort.Slice(s, func(i, j int) bool {
+                                       // Because RunParallel runs the function many
+                                       // times in parallel, we must increment the
+                                       // counter atomically to avoid racing writes.
+                                       compares.Add(1)
+                                       return s[i] < s[j]
+                               })
+                       }
+               })
+
+               // NOTE: Report each metric once, after all of the parallel
+               // calls have completed.
+
+               // This metric is per-operation, so divide by b.N and
+               // report it as a "/op" unit.
+               b.ReportMetric(float64(compares.Load())/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.Load())/float64(b.Elapsed().Nanoseconds()), "compares/ns")
+       })
+}