]> Cypherpunks.ru repositories - gostls13.git/blob - src/testing/benchmark.go
testing: only report subtest races once
[gostls13.git] / src / testing / benchmark.go
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package testing
6
7 import (
8         "flag"
9         "fmt"
10         "internal/sysinfo"
11         "io"
12         "math"
13         "os"
14         "runtime"
15         "sort"
16         "strconv"
17         "strings"
18         "sync"
19         "sync/atomic"
20         "time"
21         "unicode"
22 )
23
24 func initBenchmarkFlags() {
25         matchBenchmarks = flag.String("test.bench", "", "run only benchmarks matching `regexp`")
26         benchmarkMemory = flag.Bool("test.benchmem", false, "print memory allocations for benchmarks")
27         flag.Var(&benchTime, "test.benchtime", "run each benchmark for duration `d`")
28 }
29
30 var (
31         matchBenchmarks *string
32         benchmarkMemory *bool
33
34         benchTime = durationOrCountFlag{d: 1 * time.Second} // changed during test of testing package
35 )
36
37 type durationOrCountFlag struct {
38         d         time.Duration
39         n         int
40         allowZero bool
41 }
42
43 func (f *durationOrCountFlag) String() string {
44         if f.n > 0 {
45                 return fmt.Sprintf("%dx", f.n)
46         }
47         return f.d.String()
48 }
49
50 func (f *durationOrCountFlag) Set(s string) error {
51         if strings.HasSuffix(s, "x") {
52                 n, err := strconv.ParseInt(s[:len(s)-1], 10, 0)
53                 if err != nil || n < 0 || (!f.allowZero && n == 0) {
54                         return fmt.Errorf("invalid count")
55                 }
56                 *f = durationOrCountFlag{n: int(n)}
57                 return nil
58         }
59         d, err := time.ParseDuration(s)
60         if err != nil || d < 0 || (!f.allowZero && d == 0) {
61                 return fmt.Errorf("invalid duration")
62         }
63         *f = durationOrCountFlag{d: d}
64         return nil
65 }
66
67 // Global lock to ensure only one benchmark runs at a time.
68 var benchmarkLock sync.Mutex
69
70 // Used for every benchmark for measuring memory.
71 var memStats runtime.MemStats
72
73 // InternalBenchmark is an internal type but exported because it is cross-package;
74 // it is part of the implementation of the "go test" command.
75 type InternalBenchmark struct {
76         Name string
77         F    func(b *B)
78 }
79
80 // B is a type passed to Benchmark functions to manage benchmark
81 // timing and to specify the number of iterations to run.
82 //
83 // A benchmark ends when its Benchmark function returns or calls any of the methods
84 // FailNow, Fatal, Fatalf, SkipNow, Skip, or Skipf. Those methods must be called
85 // only from the goroutine running the Benchmark function.
86 // The other reporting methods, such as the variations of Log and Error,
87 // may be called simultaneously from multiple goroutines.
88 //
89 // Like in tests, benchmark logs are accumulated during execution
90 // and dumped to standard output when done. Unlike in tests, benchmark logs
91 // are always printed, so as not to hide output whose existence may be
92 // affecting benchmark results.
93 type B struct {
94         common
95         importPath       string // import path of the package containing the benchmark
96         context          *benchContext
97         N                int
98         previousN        int           // number of iterations in the previous run
99         previousDuration time.Duration // total duration of the previous run
100         benchFunc        func(b *B)
101         benchTime        durationOrCountFlag
102         bytes            int64
103         missingBytes     bool // one of the subbenchmarks does not have bytes set.
104         timerOn          bool
105         showAllocResult  bool
106         result           BenchmarkResult
107         parallelism      int // RunParallel creates parallelism*GOMAXPROCS goroutines
108         // The initial states of memStats.Mallocs and memStats.TotalAlloc.
109         startAllocs uint64
110         startBytes  uint64
111         // The net total of this test after being run.
112         netAllocs uint64
113         netBytes  uint64
114         // Extra metrics collected by ReportMetric.
115         extra map[string]float64
116 }
117
118 // StartTimer starts timing a test. This function is called automatically
119 // before a benchmark starts, but it can also be used to resume timing after
120 // a call to StopTimer.
121 func (b *B) StartTimer() {
122         if !b.timerOn {
123                 runtime.ReadMemStats(&memStats)
124                 b.startAllocs = memStats.Mallocs
125                 b.startBytes = memStats.TotalAlloc
126                 b.start = time.Now()
127                 b.timerOn = true
128         }
129 }
130
131 // StopTimer stops timing a test. This can be used to pause the timer
132 // while performing complex initialization that you don't
133 // want to measure.
134 func (b *B) StopTimer() {
135         if b.timerOn {
136                 b.duration += time.Since(b.start)
137                 runtime.ReadMemStats(&memStats)
138                 b.netAllocs += memStats.Mallocs - b.startAllocs
139                 b.netBytes += memStats.TotalAlloc - b.startBytes
140                 b.timerOn = false
141         }
142 }
143
144 // ResetTimer zeroes the elapsed benchmark time and memory allocation counters
145 // and deletes user-reported metrics.
146 // It does not affect whether the timer is running.
147 func (b *B) ResetTimer() {
148         if b.extra == nil {
149                 // Allocate the extra map before reading memory stats.
150                 // Pre-size it to make more allocation unlikely.
151                 b.extra = make(map[string]float64, 16)
152         } else {
153                 for k := range b.extra {
154                         delete(b.extra, k)
155                 }
156         }
157         if b.timerOn {
158                 runtime.ReadMemStats(&memStats)
159                 b.startAllocs = memStats.Mallocs
160                 b.startBytes = memStats.TotalAlloc
161                 b.start = time.Now()
162         }
163         b.duration = 0
164         b.netAllocs = 0
165         b.netBytes = 0
166 }
167
168 // SetBytes records the number of bytes processed in a single operation.
169 // If this is called, the benchmark will report ns/op and MB/s.
170 func (b *B) SetBytes(n int64) { b.bytes = n }
171
172 // ReportAllocs enables malloc statistics for this benchmark.
173 // It is equivalent to setting -test.benchmem, but it only affects the
174 // benchmark function that calls ReportAllocs.
175 func (b *B) ReportAllocs() {
176         b.showAllocResult = true
177 }
178
179 // runN runs a single benchmark for the specified number of iterations.
180 func (b *B) runN(n int) {
181         benchmarkLock.Lock()
182         defer benchmarkLock.Unlock()
183         defer b.runCleanup(normalPanic)
184         // Try to get a comparable environment for each run
185         // by clearing garbage from previous runs.
186         runtime.GC()
187         b.N = n
188         b.parallelism = 1
189         b.ResetTimer()
190         b.StartTimer()
191         b.benchFunc(b)
192         b.StopTimer()
193         b.previousN = n
194         b.previousDuration = b.duration
195         if fetchRaceErrors() > 0 {
196                 b.Errorf("race detected during execution of benchmark")
197         }
198 }
199
200 func min(x, y int64) int64 {
201         if x > y {
202                 return y
203         }
204         return x
205 }
206
207 func max(x, y int64) int64 {
208         if x < y {
209                 return y
210         }
211         return x
212 }
213
214 // run1 runs the first iteration of benchFunc. It reports whether more
215 // iterations of this benchmarks should be run.
216 func (b *B) run1() bool {
217         if ctx := b.context; ctx != nil {
218                 // Extend maxLen, if needed.
219                 if n := len(b.name) + ctx.extLen + 1; n > ctx.maxLen {
220                         ctx.maxLen = n + 8 // Add additional slack to avoid too many jumps in size.
221                 }
222         }
223         go func() {
224                 // Signal that we're done whether we return normally
225                 // or by FailNow's runtime.Goexit.
226                 defer func() {
227                         b.signal <- true
228                 }()
229
230                 b.runN(1)
231         }()
232         <-b.signal
233         if b.failed {
234                 fmt.Fprintf(b.w, "%s--- FAIL: %s\n%s", b.chatty.prefix(), b.name, b.output)
235                 return false
236         }
237         // Only print the output if we know we are not going to proceed.
238         // Otherwise it is printed in processBench.
239         b.mu.RLock()
240         finished := b.finished
241         b.mu.RUnlock()
242         if b.hasSub.Load() || finished {
243                 tag := "BENCH"
244                 if b.skipped {
245                         tag = "SKIP"
246                 }
247                 if b.chatty != nil && (len(b.output) > 0 || finished) {
248                         b.trimOutput()
249                         fmt.Fprintf(b.w, "%s--- %s: %s\n%s", b.chatty.prefix(), tag, b.name, b.output)
250                 }
251                 return false
252         }
253         return true
254 }
255
256 var labelsOnce sync.Once
257
258 // run executes the benchmark in a separate goroutine, including all of its
259 // subbenchmarks. b must not have subbenchmarks.
260 func (b *B) run() {
261         labelsOnce.Do(func() {
262                 fmt.Fprintf(b.w, "goos: %s\n", runtime.GOOS)
263                 fmt.Fprintf(b.w, "goarch: %s\n", runtime.GOARCH)
264                 if b.importPath != "" {
265                         fmt.Fprintf(b.w, "pkg: %s\n", b.importPath)
266                 }
267                 if cpu := sysinfo.CPU.Name(); cpu != "" {
268                         fmt.Fprintf(b.w, "cpu: %s\n", cpu)
269                 }
270         })
271         if b.context != nil {
272                 // Running go test --test.bench
273                 b.context.processBench(b) // Must call doBench.
274         } else {
275                 // Running func Benchmark.
276                 b.doBench()
277         }
278 }
279
280 func (b *B) doBench() BenchmarkResult {
281         go b.launch()
282         <-b.signal
283         return b.result
284 }
285
286 // launch launches the benchmark function. It gradually increases the number
287 // of benchmark iterations until the benchmark runs for the requested benchtime.
288 // launch is run by the doBench function as a separate goroutine.
289 // run1 must have been called on b.
290 func (b *B) launch() {
291         // Signal that we're done whether we return normally
292         // or by FailNow's runtime.Goexit.
293         defer func() {
294                 b.signal <- true
295         }()
296
297         // Run the benchmark for at least the specified amount of time.
298         if b.benchTime.n > 0 {
299                 // We already ran a single iteration in run1.
300                 // If -benchtime=1x was requested, use that result.
301                 // See https://golang.org/issue/32051.
302                 if b.benchTime.n > 1 {
303                         b.runN(b.benchTime.n)
304                 }
305         } else {
306                 d := b.benchTime.d
307                 for n := int64(1); !b.failed && b.duration < d && n < 1e9; {
308                         last := n
309                         // Predict required iterations.
310                         goalns := d.Nanoseconds()
311                         prevIters := int64(b.N)
312                         prevns := b.duration.Nanoseconds()
313                         if prevns <= 0 {
314                                 // Round up, to avoid div by zero.
315                                 prevns = 1
316                         }
317                         // Order of operations matters.
318                         // For very fast benchmarks, prevIters ~= prevns.
319                         // If you divide first, you get 0 or 1,
320                         // which can hide an order of magnitude in execution time.
321                         // So multiply first, then divide.
322                         n = goalns * prevIters / prevns
323                         // Run more iterations than we think we'll need (1.2x).
324                         n += n / 5
325                         // Don't grow too fast in case we had timing errors previously.
326                         n = min(n, 100*last)
327                         // Be sure to run at least one more than last time.
328                         n = max(n, last+1)
329                         // Don't run more than 1e9 times. (This also keeps n in int range on 32 bit platforms.)
330                         n = min(n, 1e9)
331                         b.runN(int(n))
332                 }
333         }
334         b.result = BenchmarkResult{b.N, b.duration, b.bytes, b.netAllocs, b.netBytes, b.extra}
335 }
336
337 // Elapsed returns the measured elapsed time of the benchmark.
338 // The duration reported by Elapsed matches the one measured by
339 // StartTimer, StopTimer, and ResetTimer.
340 func (b *B) Elapsed() time.Duration {
341         d := b.duration
342         if b.timerOn {
343                 d += time.Since(b.start)
344         }
345         return d
346 }
347
348 // ReportMetric adds "n unit" to the reported benchmark results.
349 // If the metric is per-iteration, the caller should divide by b.N,
350 // and by convention units should end in "/op".
351 // ReportMetric overrides any previously reported value for the same unit.
352 // ReportMetric panics if unit is the empty string or if unit contains
353 // any whitespace.
354 // If unit is a unit normally reported by the benchmark framework itself
355 // (such as "allocs/op"), ReportMetric will override that metric.
356 // Setting "ns/op" to 0 will suppress that built-in metric.
357 func (b *B) ReportMetric(n float64, unit string) {
358         if unit == "" {
359                 panic("metric unit must not be empty")
360         }
361         if strings.IndexFunc(unit, unicode.IsSpace) >= 0 {
362                 panic("metric unit must not contain whitespace")
363         }
364         b.extra[unit] = n
365 }
366
367 // BenchmarkResult contains the results of a benchmark run.
368 type BenchmarkResult struct {
369         N         int           // The number of iterations.
370         T         time.Duration // The total time taken.
371         Bytes     int64         // Bytes processed in one iteration.
372         MemAllocs uint64        // The total number of memory allocations.
373         MemBytes  uint64        // The total number of bytes allocated.
374
375         // Extra records additional metrics reported by ReportMetric.
376         Extra map[string]float64
377 }
378
379 // NsPerOp returns the "ns/op" metric.
380 func (r BenchmarkResult) NsPerOp() int64 {
381         if v, ok := r.Extra["ns/op"]; ok {
382                 return int64(v)
383         }
384         if r.N <= 0 {
385                 return 0
386         }
387         return r.T.Nanoseconds() / int64(r.N)
388 }
389
390 // mbPerSec returns the "MB/s" metric.
391 func (r BenchmarkResult) mbPerSec() float64 {
392         if v, ok := r.Extra["MB/s"]; ok {
393                 return v
394         }
395         if r.Bytes <= 0 || r.T <= 0 || r.N <= 0 {
396                 return 0
397         }
398         return (float64(r.Bytes) * float64(r.N) / 1e6) / r.T.Seconds()
399 }
400
401 // AllocsPerOp returns the "allocs/op" metric,
402 // which is calculated as r.MemAllocs / r.N.
403 func (r BenchmarkResult) AllocsPerOp() int64 {
404         if v, ok := r.Extra["allocs/op"]; ok {
405                 return int64(v)
406         }
407         if r.N <= 0 {
408                 return 0
409         }
410         return int64(r.MemAllocs) / int64(r.N)
411 }
412
413 // AllocedBytesPerOp returns the "B/op" metric,
414 // which is calculated as r.MemBytes / r.N.
415 func (r BenchmarkResult) AllocedBytesPerOp() int64 {
416         if v, ok := r.Extra["B/op"]; ok {
417                 return int64(v)
418         }
419         if r.N <= 0 {
420                 return 0
421         }
422         return int64(r.MemBytes) / int64(r.N)
423 }
424
425 // String returns a summary of the benchmark results.
426 // It follows the benchmark result line format from
427 // https://golang.org/design/14313-benchmark-format, not including the
428 // benchmark name.
429 // Extra metrics override built-in metrics of the same name.
430 // String does not include allocs/op or B/op, since those are reported
431 // by MemString.
432 func (r BenchmarkResult) String() string {
433         buf := new(strings.Builder)
434         fmt.Fprintf(buf, "%8d", r.N)
435
436         // Get ns/op as a float.
437         ns, ok := r.Extra["ns/op"]
438         if !ok {
439                 ns = float64(r.T.Nanoseconds()) / float64(r.N)
440         }
441         if ns != 0 {
442                 buf.WriteByte('\t')
443                 prettyPrint(buf, ns, "ns/op")
444         }
445
446         if mbs := r.mbPerSec(); mbs != 0 {
447                 fmt.Fprintf(buf, "\t%7.2f MB/s", mbs)
448         }
449
450         // Print extra metrics that aren't represented in the standard
451         // metrics.
452         var extraKeys []string
453         for k := range r.Extra {
454                 switch k {
455                 case "ns/op", "MB/s", "B/op", "allocs/op":
456                         // Built-in metrics reported elsewhere.
457                         continue
458                 }
459                 extraKeys = append(extraKeys, k)
460         }
461         sort.Strings(extraKeys)
462         for _, k := range extraKeys {
463                 buf.WriteByte('\t')
464                 prettyPrint(buf, r.Extra[k], k)
465         }
466         return buf.String()
467 }
468
469 func prettyPrint(w io.Writer, x float64, unit string) {
470         // Print all numbers with 10 places before the decimal point
471         // and small numbers with four sig figs. Field widths are
472         // chosen to fit the whole part in 10 places while aligning
473         // the decimal point of all fractional formats.
474         var format string
475         switch y := math.Abs(x); {
476         case y == 0 || y >= 999.95:
477                 format = "%10.0f %s"
478         case y >= 99.995:
479                 format = "%12.1f %s"
480         case y >= 9.9995:
481                 format = "%13.2f %s"
482         case y >= 0.99995:
483                 format = "%14.3f %s"
484         case y >= 0.099995:
485                 format = "%15.4f %s"
486         case y >= 0.0099995:
487                 format = "%16.5f %s"
488         case y >= 0.00099995:
489                 format = "%17.6f %s"
490         default:
491                 format = "%18.7f %s"
492         }
493         fmt.Fprintf(w, format, x, unit)
494 }
495
496 // MemString returns r.AllocedBytesPerOp and r.AllocsPerOp in the same format as 'go test'.
497 func (r BenchmarkResult) MemString() string {
498         return fmt.Sprintf("%8d B/op\t%8d allocs/op",
499                 r.AllocedBytesPerOp(), r.AllocsPerOp())
500 }
501
502 // benchmarkName returns full name of benchmark including procs suffix.
503 func benchmarkName(name string, n int) string {
504         if n != 1 {
505                 return fmt.Sprintf("%s-%d", name, n)
506         }
507         return name
508 }
509
510 type benchContext struct {
511         match *matcher
512
513         maxLen int // The largest recorded benchmark name.
514         extLen int // Maximum extension length.
515 }
516
517 // RunBenchmarks is an internal function but exported because it is cross-package;
518 // it is part of the implementation of the "go test" command.
519 func RunBenchmarks(matchString func(pat, str string) (bool, error), benchmarks []InternalBenchmark) {
520         runBenchmarks("", matchString, benchmarks)
521 }
522
523 func runBenchmarks(importPath string, matchString func(pat, str string) (bool, error), benchmarks []InternalBenchmark) bool {
524         // If no flag was specified, don't run benchmarks.
525         if len(*matchBenchmarks) == 0 {
526                 return true
527         }
528         // Collect matching benchmarks and determine longest name.
529         maxprocs := 1
530         for _, procs := range cpuList {
531                 if procs > maxprocs {
532                         maxprocs = procs
533                 }
534         }
535         ctx := &benchContext{
536                 match:  newMatcher(matchString, *matchBenchmarks, "-test.bench", *skip),
537                 extLen: len(benchmarkName("", maxprocs)),
538         }
539         var bs []InternalBenchmark
540         for _, Benchmark := range benchmarks {
541                 if _, matched, _ := ctx.match.fullName(nil, Benchmark.Name); matched {
542                         bs = append(bs, Benchmark)
543                         benchName := benchmarkName(Benchmark.Name, maxprocs)
544                         if l := len(benchName) + ctx.extLen + 1; l > ctx.maxLen {
545                                 ctx.maxLen = l
546                         }
547                 }
548         }
549         main := &B{
550                 common: common{
551                         name:  "Main",
552                         w:     os.Stdout,
553                         bench: true,
554                 },
555                 importPath: importPath,
556                 benchFunc: func(b *B) {
557                         for _, Benchmark := range bs {
558                                 b.Run(Benchmark.Name, Benchmark.F)
559                         }
560                 },
561                 benchTime: benchTime,
562                 context:   ctx,
563         }
564         if Verbose() {
565                 main.chatty = newChattyPrinter(main.w)
566         }
567         main.runN(1)
568         return !main.failed
569 }
570
571 // processBench runs bench b for the configured CPU counts and prints the results.
572 func (ctx *benchContext) processBench(b *B) {
573         for i, procs := range cpuList {
574                 for j := uint(0); j < *count; j++ {
575                         runtime.GOMAXPROCS(procs)
576                         benchName := benchmarkName(b.name, procs)
577
578                         // If it's chatty, we've already printed this information.
579                         if b.chatty == nil {
580                                 fmt.Fprintf(b.w, "%-*s\t", ctx.maxLen, benchName)
581                         }
582                         // Recompute the running time for all but the first iteration.
583                         if i > 0 || j > 0 {
584                                 b = &B{
585                                         common: common{
586                                                 signal: make(chan bool),
587                                                 name:   b.name,
588                                                 w:      b.w,
589                                                 chatty: b.chatty,
590                                                 bench:  true,
591                                         },
592                                         benchFunc: b.benchFunc,
593                                         benchTime: b.benchTime,
594                                 }
595                                 b.run1()
596                         }
597                         r := b.doBench()
598                         if b.failed {
599                                 // The output could be very long here, but probably isn't.
600                                 // We print it all, regardless, because we don't want to trim the reason
601                                 // the benchmark failed.
602                                 fmt.Fprintf(b.w, "%s--- FAIL: %s\n%s", b.chatty.prefix(), benchName, b.output)
603                                 continue
604                         }
605                         results := r.String()
606                         if b.chatty != nil {
607                                 fmt.Fprintf(b.w, "%-*s\t", ctx.maxLen, benchName)
608                         }
609                         if *benchmarkMemory || b.showAllocResult {
610                                 results += "\t" + r.MemString()
611                         }
612                         fmt.Fprintln(b.w, results)
613                         // Unlike with tests, we ignore the -chatty flag and always print output for
614                         // benchmarks since the output generation time will skew the results.
615                         if len(b.output) > 0 {
616                                 b.trimOutput()
617                                 fmt.Fprintf(b.w, "%s--- BENCH: %s\n%s", b.chatty.prefix(), benchName, b.output)
618                         }
619                         if p := runtime.GOMAXPROCS(-1); p != procs {
620                                 fmt.Fprintf(os.Stderr, "testing: %s left GOMAXPROCS set to %d\n", benchName, p)
621                         }
622                         if b.chatty != nil && b.chatty.json {
623                                 b.chatty.Updatef("", "=== NAME  %s\n", "")
624                         }
625                 }
626         }
627 }
628
629 // If hideStdoutForTesting is true, Run does not print the benchName.
630 // This avoids a spurious print during 'go test' on package testing itself,
631 // which invokes b.Run in its own tests (see sub_test.go).
632 var hideStdoutForTesting = false
633
634 // Run benchmarks f as a subbenchmark with the given name. It reports
635 // whether there were any failures.
636 //
637 // A subbenchmark is like any other benchmark. A benchmark that calls Run at
638 // least once will not be measured itself and will be called once with N=1.
639 func (b *B) Run(name string, f func(b *B)) bool {
640         // Since b has subbenchmarks, we will no longer run it as a benchmark itself.
641         // Release the lock and acquire it on exit to ensure locks stay paired.
642         b.hasSub.Store(true)
643         benchmarkLock.Unlock()
644         defer benchmarkLock.Lock()
645
646         benchName, ok, partial := b.name, true, false
647         if b.context != nil {
648                 benchName, ok, partial = b.context.match.fullName(&b.common, name)
649         }
650         if !ok {
651                 return true
652         }
653         var pc [maxStackLen]uintptr
654         n := runtime.Callers(2, pc[:])
655         sub := &B{
656                 common: common{
657                         signal:  make(chan bool),
658                         name:    benchName,
659                         parent:  &b.common,
660                         level:   b.level + 1,
661                         creator: pc[:n],
662                         w:       b.w,
663                         chatty:  b.chatty,
664                         bench:   true,
665                 },
666                 importPath: b.importPath,
667                 benchFunc:  f,
668                 benchTime:  b.benchTime,
669                 context:    b.context,
670         }
671         if partial {
672                 // Partial name match, like -bench=X/Y matching BenchmarkX.
673                 // Only process sub-benchmarks, if any.
674                 sub.hasSub.Store(true)
675         }
676
677         if b.chatty != nil {
678                 labelsOnce.Do(func() {
679                         fmt.Printf("goos: %s\n", runtime.GOOS)
680                         fmt.Printf("goarch: %s\n", runtime.GOARCH)
681                         if b.importPath != "" {
682                                 fmt.Printf("pkg: %s\n", b.importPath)
683                         }
684                         if cpu := sysinfo.CPU.Name(); cpu != "" {
685                                 fmt.Printf("cpu: %s\n", cpu)
686                         }
687                 })
688
689                 if !hideStdoutForTesting {
690                         if b.chatty.json {
691                                 b.chatty.Updatef(benchName, "=== RUN   %s\n", benchName)
692                         }
693                         fmt.Println(benchName)
694                 }
695         }
696
697         if sub.run1() {
698                 sub.run()
699         }
700         b.add(sub.result)
701         return !sub.failed
702 }
703
704 // add simulates running benchmarks in sequence in a single iteration. It is
705 // used to give some meaningful results in case func Benchmark is used in
706 // combination with Run.
707 func (b *B) add(other BenchmarkResult) {
708         r := &b.result
709         // The aggregated BenchmarkResults resemble running all subbenchmarks as
710         // in sequence in a single benchmark.
711         r.N = 1
712         r.T += time.Duration(other.NsPerOp())
713         if other.Bytes == 0 {
714                 // Summing Bytes is meaningless in aggregate if not all subbenchmarks
715                 // set it.
716                 b.missingBytes = true
717                 r.Bytes = 0
718         }
719         if !b.missingBytes {
720                 r.Bytes += other.Bytes
721         }
722         r.MemAllocs += uint64(other.AllocsPerOp())
723         r.MemBytes += uint64(other.AllocedBytesPerOp())
724 }
725
726 // trimOutput shortens the output from a benchmark, which can be very long.
727 func (b *B) trimOutput() {
728         // The output is likely to appear multiple times because the benchmark
729         // is run multiple times, but at least it will be seen. This is not a big deal
730         // because benchmarks rarely print, but just in case, we trim it if it's too long.
731         const maxNewlines = 10
732         for nlCount, j := 0, 0; j < len(b.output); j++ {
733                 if b.output[j] == '\n' {
734                         nlCount++
735                         if nlCount >= maxNewlines {
736                                 b.output = append(b.output[:j], "\n\t... [output truncated]\n"...)
737                                 break
738                         }
739                 }
740         }
741 }
742
743 // A PB is used by RunParallel for running parallel benchmarks.
744 type PB struct {
745         globalN *uint64 // shared between all worker goroutines iteration counter
746         grain   uint64  // acquire that many iterations from globalN at once
747         cache   uint64  // local cache of acquired iterations
748         bN      uint64  // total number of iterations to execute (b.N)
749 }
750
751 // Next reports whether there are more iterations to execute.
752 func (pb *PB) Next() bool {
753         if pb.cache == 0 {
754                 n := atomic.AddUint64(pb.globalN, pb.grain)
755                 if n <= pb.bN {
756                         pb.cache = pb.grain
757                 } else if n < pb.bN+pb.grain {
758                         pb.cache = pb.bN + pb.grain - n
759                 } else {
760                         return false
761                 }
762         }
763         pb.cache--
764         return true
765 }
766
767 // RunParallel runs a benchmark in parallel.
768 // It creates multiple goroutines and distributes b.N iterations among them.
769 // The number of goroutines defaults to GOMAXPROCS. To increase parallelism for
770 // non-CPU-bound benchmarks, call SetParallelism before RunParallel.
771 // RunParallel is usually used with the go test -cpu flag.
772 //
773 // The body function will be run in each goroutine. It should set up any
774 // goroutine-local state and then iterate until pb.Next returns false.
775 // It should not use the StartTimer, StopTimer, or ResetTimer functions,
776 // because they have global effect. It should also not call Run.
777 //
778 // RunParallel reports ns/op values as wall time for the benchmark as a whole,
779 // not the sum of wall time or CPU time over each parallel goroutine.
780 func (b *B) RunParallel(body func(*PB)) {
781         if b.N == 0 {
782                 return // Nothing to do when probing.
783         }
784         // Calculate grain size as number of iterations that take ~100µs.
785         // 100µs is enough to amortize the overhead and provide sufficient
786         // dynamic load balancing.
787         grain := uint64(0)
788         if b.previousN > 0 && b.previousDuration > 0 {
789                 grain = 1e5 * uint64(b.previousN) / uint64(b.previousDuration)
790         }
791         if grain < 1 {
792                 grain = 1
793         }
794         // We expect the inner loop and function call to take at least 10ns,
795         // so do not do more than 100µs/10ns=1e4 iterations.
796         if grain > 1e4 {
797                 grain = 1e4
798         }
799
800         n := uint64(0)
801         numProcs := b.parallelism * runtime.GOMAXPROCS(0)
802         var wg sync.WaitGroup
803         wg.Add(numProcs)
804         for p := 0; p < numProcs; p++ {
805                 go func() {
806                         defer wg.Done()
807                         pb := &PB{
808                                 globalN: &n,
809                                 grain:   grain,
810                                 bN:      uint64(b.N),
811                         }
812                         body(pb)
813                 }()
814         }
815         wg.Wait()
816         if n <= uint64(b.N) && !b.Failed() {
817                 b.Fatal("RunParallel: body exited without pb.Next() == false")
818         }
819 }
820
821 // SetParallelism sets the number of goroutines used by RunParallel to p*GOMAXPROCS.
822 // There is usually no need to call SetParallelism for CPU-bound benchmarks.
823 // If p is less than 1, this call will have no effect.
824 func (b *B) SetParallelism(p int) {
825         if p >= 1 {
826                 b.parallelism = p
827         }
828 }
829
830 // Benchmark benchmarks a single function. It is useful for creating
831 // custom benchmarks that do not use the "go test" command.
832 //
833 // If f depends on testing flags, then Init must be used to register
834 // those flags before calling Benchmark and before calling flag.Parse.
835 //
836 // If f calls Run, the result will be an estimate of running all its
837 // subbenchmarks that don't call Run in sequence in a single benchmark.
838 func Benchmark(f func(b *B)) BenchmarkResult {
839         b := &B{
840                 common: common{
841                         signal: make(chan bool),
842                         w:      discard{},
843                 },
844                 benchFunc: f,
845                 benchTime: benchTime,
846         }
847         if b.run1() {
848                 b.run()
849         }
850         return b.result
851 }
852
853 type discard struct{}
854
855 func (discard) Write(b []byte) (n int, err error) { return len(b), nil }