Skip to content

Commit

Permalink
testing: add an example of using ReportMetric within a parallel bench…
Browse files Browse the repository at this point in the history
…mark.

Show how to use b.N within a parallel benchmark at the setup and
reporting phases of the benchmark. Indicate that atomic operations must
be used within the benchmark for loop and that b.N can reliably be
derefenced from outside of the benchmark for loop.

Fixes golang#50756
  • Loading branch information
elisshafer committed Jun 29, 2022
1 parent b6c1606 commit ecc09a5
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/testing/benchmark_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package testing_test

import (
"bytes"
"fmt"
"runtime"
"sort"
"strings"
Expand Down Expand Up @@ -178,3 +179,27 @@ func ExampleB_ReportMetric() {
b.ReportMetric(float64(compares)/float64(b.N), "compares/op")
})
}

func ExampleB_ReportMetric_parallel() {
// This reports a custom benchmark metric recorded during a
// parallel benchmark.
testing.Benchmark(func(b *testing.B) {
var compares int64
fmt.Printf("Running the benchmark %d times...\n", b.N)
b.RunParallel(func(pb *testing.PB) {
// Use pb.Next to determine whether there is another scheduled goroutine.
for pb.Next() {
s := []int{5, 4, 3, 2, 1}
sort.Slice(s, func(i, j int) bool {
// Use the atomic package to avoid a race condition as
// the body of the for loop will be executed concurrently.
atomic.AddInt64(&compares, 1)
return s[i] < s[j]
})
}
})
// b.N is safe to use as the total number of iterations outside
// the benchmark for loop, either for the setup or teardown.
b.ReportMetric(float64(compares)/float64(b.N), "compares/op")
})
}

0 comments on commit ecc09a5

Please sign in to comment.