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