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.
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`")
32 matchBenchmarks *string
35 benchTime = benchTimeFlag{d: 1 * time.Second} // changed during test of testing package
38 type benchTimeFlag struct {
43 func (f *benchTimeFlag) String() string {
45 return fmt.Sprintf("%dx", f.n)
47 return time.Duration(f.d).String()
50 func (f *benchTimeFlag) 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 {
54 return fmt.Errorf("invalid count")
56 *f = benchTimeFlag{n: int(n)}
59 d, err := time.ParseDuration(s)
60 if err != nil || d <= 0 {
61 return fmt.Errorf("invalid duration")
63 *f = benchTimeFlag{d: d}
67 // Global lock to ensure only one benchmark runs at a time.
68 var benchmarkLock sync.Mutex
70 // Used for every benchmark for measuring memory.
71 var memStats runtime.MemStats
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 {
80 // B is a type passed to Benchmark functions to manage benchmark
81 // timing and to specify the number of iterations to run.
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.
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.
95 importPath string // import path of the package containing the benchmark
98 previousN int // number of iterations in the previous run
99 previousDuration time.Duration // total duration of the previous run
101 benchTime benchTimeFlag
103 missingBytes bool // one of the subbenchmarks does not have bytes set.
106 result BenchmarkResult
107 parallelism int // RunParallel creates parallelism*GOMAXPROCS goroutines
108 // The initial states of memStats.Mallocs and memStats.TotalAlloc.
111 // The net total of this test after being run.
114 // Extra metrics collected by ReportMetric.
115 extra map[string]float64
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() {
123 runtime.ReadMemStats(&memStats)
124 b.startAllocs = memStats.Mallocs
125 b.startBytes = memStats.TotalAlloc
131 // StopTimer stops timing a test. This can be used to pause the timer
132 // while performing complex initialization that you don't
134 func (b *B) StopTimer() {
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
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() {
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)
153 for k := range b.extra {
158 runtime.ReadMemStats(&memStats)
159 b.startAllocs = memStats.Mallocs
160 b.startBytes = memStats.TotalAlloc
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 }
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
179 // runN runs a single benchmark for the specified number of iterations.
180 func (b *B) runN(n int) {
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.
187 b.raceErrors = -race.Errors()
195 b.previousDuration = b.duration
196 b.raceErrors += race.Errors()
197 if b.raceErrors > 0 {
198 b.Errorf("race detected during execution of benchmark")
202 func min(x, y int64) int64 {
209 func max(x, y int64) int64 {
216 // run1 runs the first iteration of benchFunc. It reports whether more
217 // iterations of this benchmarks should be run.
218 func (b *B) run1() bool {
219 if ctx := b.context; ctx != nil {
220 // Extend maxLen, if needed.
221 if n := len(b.name) + ctx.extLen + 1; n > ctx.maxLen {
222 ctx.maxLen = n + 8 // Add additional slack to avoid too many jumps in size.
226 // Signal that we're done whether we return normally
227 // or by FailNow's runtime.Goexit.
236 fmt.Fprintf(b.w, "--- FAIL: %s\n%s", b.name, b.output)
239 // Only print the output if we know we are not going to proceed.
240 // Otherwise it is printed in processBench.
241 if atomic.LoadInt32(&b.hasSub) != 0 || b.finished {
246 if b.chatty != nil && (len(b.output) > 0 || b.finished) {
248 fmt.Fprintf(b.w, "--- %s: %s\n%s", tag, b.name, b.output)
255 var labelsOnce sync.Once
257 // run executes the benchmark in a separate goroutine, including all of its
258 // subbenchmarks. b must not have subbenchmarks.
260 labelsOnce.Do(func() {
261 fmt.Fprintf(b.w, "goos: %s\n", runtime.GOOS)
262 fmt.Fprintf(b.w, "goarch: %s\n", runtime.GOARCH)
263 if b.importPath != "" {
264 fmt.Fprintf(b.w, "pkg: %s\n", b.importPath)
266 if cpu := sysinfo.CPU.Name(); cpu != "" {
267 fmt.Fprintf(b.w, "cpu: %s\n", cpu)
270 if b.context != nil {
271 // Running go test --test.bench
272 b.context.processBench(b) // Must call doBench.
274 // Running func Benchmark.
279 func (b *B) doBench() BenchmarkResult {
285 // launch launches the benchmark function. It gradually increases the number
286 // of benchmark iterations until the benchmark runs for the requested benchtime.
287 // launch is run by the doBench function as a separate goroutine.
288 // run1 must have been called on b.
289 func (b *B) launch() {
290 // Signal that we're done whether we return normally
291 // or by FailNow's runtime.Goexit.
296 // Run the benchmark for at least the specified amount of time.
297 if b.benchTime.n > 0 {
298 b.runN(b.benchTime.n)
301 for n := int64(1); !b.failed && b.duration < d && n < 1e9; {
303 // Predict required iterations.
304 goalns := d.Nanoseconds()
305 prevIters := int64(b.N)
306 prevns := b.duration.Nanoseconds()
308 // Round up, to avoid div by zero.
311 // Order of operations matters.
312 // For very fast benchmarks, prevIters ~= prevns.
313 // If you divide first, you get 0 or 1,
314 // which can hide an order of magnitude in execution time.
315 // So multiply first, then divide.
316 n = goalns * prevIters / prevns
317 // Run more iterations than we think we'll need (1.2x).
319 // Don't grow too fast in case we had timing errors previously.
321 // Be sure to run at least one more than last time.
323 // Don't run more than 1e9 times. (This also keeps n in int range on 32 bit platforms.)
328 b.result = BenchmarkResult{b.N, b.duration, b.bytes, b.netAllocs, b.netBytes, b.extra}
331 // ReportMetric adds "n unit" to the reported benchmark results.
332 // If the metric is per-iteration, the caller should divide by b.N,
333 // and by convention units should end in "/op".
334 // ReportMetric overrides any previously reported value for the same unit.
335 // ReportMetric panics if unit is the empty string or if unit contains
337 // If unit is a unit normally reported by the benchmark framework itself
338 // (such as "allocs/op"), ReportMetric will override that metric.
339 // Setting "ns/op" to 0 will suppress that built-in metric.
340 func (b *B) ReportMetric(n float64, unit string) {
342 panic("metric unit must not be empty")
344 if strings.IndexFunc(unit, unicode.IsSpace) >= 0 {
345 panic("metric unit must not contain whitespace")
350 // BenchmarkResult contains the results of a benchmark run.
351 type BenchmarkResult struct {
352 N int // The number of iterations.
353 T time.Duration // The total time taken.
354 Bytes int64 // Bytes processed in one iteration.
355 MemAllocs uint64 // The total number of memory allocations.
356 MemBytes uint64 // The total number of bytes allocated.
358 // Extra records additional metrics reported by ReportMetric.
359 Extra map[string]float64
362 // NsPerOp returns the "ns/op" metric.
363 func (r BenchmarkResult) NsPerOp() int64 {
364 if v, ok := r.Extra["ns/op"]; ok {
370 return r.T.Nanoseconds() / int64(r.N)
373 // mbPerSec returns the "MB/s" metric.
374 func (r BenchmarkResult) mbPerSec() float64 {
375 if v, ok := r.Extra["MB/s"]; ok {
378 if r.Bytes <= 0 || r.T <= 0 || r.N <= 0 {
381 return (float64(r.Bytes) * float64(r.N) / 1e6) / r.T.Seconds()
384 // AllocsPerOp returns the "allocs/op" metric,
385 // which is calculated as r.MemAllocs / r.N.
386 func (r BenchmarkResult) AllocsPerOp() int64 {
387 if v, ok := r.Extra["allocs/op"]; ok {
393 return int64(r.MemAllocs) / int64(r.N)
396 // AllocedBytesPerOp returns the "B/op" metric,
397 // which is calculated as r.MemBytes / r.N.
398 func (r BenchmarkResult) AllocedBytesPerOp() int64 {
399 if v, ok := r.Extra["B/op"]; ok {
405 return int64(r.MemBytes) / int64(r.N)
408 // String returns a summary of the benchmark results.
409 // It follows the benchmark result line format from
410 // https://golang.org/design/14313-benchmark-format, not including the
412 // Extra metrics override built-in metrics of the same name.
413 // String does not include allocs/op or B/op, since those are reported
415 func (r BenchmarkResult) String() string {
416 buf := new(strings.Builder)
417 fmt.Fprintf(buf, "%8d", r.N)
419 // Get ns/op as a float.
420 ns, ok := r.Extra["ns/op"]
422 ns = float64(r.T.Nanoseconds()) / float64(r.N)
426 prettyPrint(buf, ns, "ns/op")
429 if mbs := r.mbPerSec(); mbs != 0 {
430 fmt.Fprintf(buf, "\t%7.2f MB/s", mbs)
433 // Print extra metrics that aren't represented in the standard
435 var extraKeys []string
436 for k := range r.Extra {
438 case "ns/op", "MB/s", "B/op", "allocs/op":
439 // Built-in metrics reported elsewhere.
442 extraKeys = append(extraKeys, k)
444 sort.Strings(extraKeys)
445 for _, k := range extraKeys {
447 prettyPrint(buf, r.Extra[k], k)
452 func prettyPrint(w io.Writer, x float64, unit string) {
453 // Print all numbers with 10 places before the decimal point
454 // and small numbers with four sig figs. Field widths are
455 // chosen to fit the whole part in 10 places while aligning
456 // the decimal point of all fractional formats.
458 switch y := math.Abs(x); {
459 case y == 0 || y >= 999.95:
471 case y >= 0.00099995:
476 fmt.Fprintf(w, format, x, unit)
479 // MemString returns r.AllocedBytesPerOp and r.AllocsPerOp in the same format as 'go test'.
480 func (r BenchmarkResult) MemString() string {
481 return fmt.Sprintf("%8d B/op\t%8d allocs/op",
482 r.AllocedBytesPerOp(), r.AllocsPerOp())
485 // benchmarkName returns full name of benchmark including procs suffix.
486 func benchmarkName(name string, n int) string {
488 return fmt.Sprintf("%s-%d", name, n)
493 type benchContext struct {
496 maxLen int // The largest recorded benchmark name.
497 extLen int // Maximum extension length.
500 // RunBenchmarks is an internal function but exported because it is cross-package;
501 // it is part of the implementation of the "go test" command.
502 func RunBenchmarks(matchString func(pat, str string) (bool, error), benchmarks []InternalBenchmark) {
503 runBenchmarks("", matchString, benchmarks)
506 func runBenchmarks(importPath string, matchString func(pat, str string) (bool, error), benchmarks []InternalBenchmark) bool {
507 // If no flag was specified, don't run benchmarks.
508 if len(*matchBenchmarks) == 0 {
511 // Collect matching benchmarks and determine longest name.
513 for _, procs := range cpuList {
514 if procs > maxprocs {
518 ctx := &benchContext{
519 match: newMatcher(matchString, *matchBenchmarks, "-test.bench"),
520 extLen: len(benchmarkName("", maxprocs)),
522 var bs []InternalBenchmark
523 for _, Benchmark := range benchmarks {
524 if _, matched, _ := ctx.match.fullName(nil, Benchmark.Name); matched {
525 bs = append(bs, Benchmark)
526 benchName := benchmarkName(Benchmark.Name, maxprocs)
527 if l := len(benchName) + ctx.extLen + 1; l > ctx.maxLen {
538 importPath: importPath,
539 benchFunc: func(b *B) {
540 for _, Benchmark := range bs {
541 b.Run(Benchmark.Name, Benchmark.F)
544 benchTime: benchTime,
548 main.chatty = newChattyPrinter(main.w)
554 // processBench runs bench b for the configured CPU counts and prints the results.
555 func (ctx *benchContext) processBench(b *B) {
556 for i, procs := range cpuList {
557 for j := uint(0); j < *count; j++ {
558 runtime.GOMAXPROCS(procs)
559 benchName := benchmarkName(b.name, procs)
561 // If it's chatty, we've already printed this information.
563 fmt.Fprintf(b.w, "%-*s\t", ctx.maxLen, benchName)
565 // Recompute the running time for all but the first iteration.
569 signal: make(chan bool),
575 benchFunc: b.benchFunc,
576 benchTime: b.benchTime,
582 // The output could be very long here, but probably isn't.
583 // We print it all, regardless, because we don't want to trim the reason
584 // the benchmark failed.
585 fmt.Fprintf(b.w, "--- FAIL: %s\n%s", benchName, b.output)
588 results := r.String()
590 fmt.Fprintf(b.w, "%-*s\t", ctx.maxLen, benchName)
592 if *benchmarkMemory || b.showAllocResult {
593 results += "\t" + r.MemString()
595 fmt.Fprintln(b.w, results)
596 // Unlike with tests, we ignore the -chatty flag and always print output for
597 // benchmarks since the output generation time will skew the results.
598 if len(b.output) > 0 {
600 fmt.Fprintf(b.w, "--- BENCH: %s\n%s", benchName, b.output)
602 if p := runtime.GOMAXPROCS(-1); p != procs {
603 fmt.Fprintf(os.Stderr, "testing: %s left GOMAXPROCS set to %d\n", benchName, p)
609 // Run benchmarks f as a subbenchmark with the given name. It reports
610 // whether there were any failures.
612 // A subbenchmark is like any other benchmark. A benchmark that calls Run at
613 // least once will not be measured itself and will be called once with N=1.
614 func (b *B) Run(name string, f func(b *B)) bool {
615 // Since b has subbenchmarks, we will no longer run it as a benchmark itself.
616 // Release the lock and acquire it on exit to ensure locks stay paired.
617 atomic.StoreInt32(&b.hasSub, 1)
618 benchmarkLock.Unlock()
619 defer benchmarkLock.Lock()
621 benchName, ok, partial := b.name, true, false
622 if b.context != nil {
623 benchName, ok, partial = b.context.match.fullName(&b.common, name)
628 var pc [maxStackLen]uintptr
629 n := runtime.Callers(2, pc[:])
632 signal: make(chan bool),
641 importPath: b.importPath,
643 benchTime: b.benchTime,
647 // Partial name match, like -bench=X/Y matching BenchmarkX.
648 // Only process sub-benchmarks, if any.
649 atomic.StoreInt32(&sub.hasSub, 1)
653 labelsOnce.Do(func() {
654 fmt.Printf("goos: %s\n", runtime.GOOS)
655 fmt.Printf("goarch: %s\n", runtime.GOARCH)
656 if b.importPath != "" {
657 fmt.Printf("pkg: %s\n", b.importPath)
659 if cpu := sysinfo.CPU.Name(); cpu != "" {
660 fmt.Printf("cpu: %s\n", cpu)
664 fmt.Println(benchName)
674 // add simulates running benchmarks in sequence in a single iteration. It is
675 // used to give some meaningful results in case func Benchmark is used in
676 // combination with Run.
677 func (b *B) add(other BenchmarkResult) {
679 // The aggregated BenchmarkResults resemble running all subbenchmarks as
680 // in sequence in a single benchmark.
682 r.T += time.Duration(other.NsPerOp())
683 if other.Bytes == 0 {
684 // Summing Bytes is meaningless in aggregate if not all subbenchmarks
686 b.missingBytes = true
690 r.Bytes += other.Bytes
692 r.MemAllocs += uint64(other.AllocsPerOp())
693 r.MemBytes += uint64(other.AllocedBytesPerOp())
696 // trimOutput shortens the output from a benchmark, which can be very long.
697 func (b *B) trimOutput() {
698 // The output is likely to appear multiple times because the benchmark
699 // is run multiple times, but at least it will be seen. This is not a big deal
700 // because benchmarks rarely print, but just in case, we trim it if it's too long.
701 const maxNewlines = 10
702 for nlCount, j := 0, 0; j < len(b.output); j++ {
703 if b.output[j] == '\n' {
705 if nlCount >= maxNewlines {
706 b.output = append(b.output[:j], "\n\t... [output truncated]\n"...)
713 // A PB is used by RunParallel for running parallel benchmarks.
715 globalN *uint64 // shared between all worker goroutines iteration counter
716 grain uint64 // acquire that many iterations from globalN at once
717 cache uint64 // local cache of acquired iterations
718 bN uint64 // total number of iterations to execute (b.N)
721 // Next reports whether there are more iterations to execute.
722 func (pb *PB) Next() bool {
724 n := atomic.AddUint64(pb.globalN, pb.grain)
727 } else if n < pb.bN+pb.grain {
728 pb.cache = pb.bN + pb.grain - n
737 // RunParallel runs a benchmark in parallel.
738 // It creates multiple goroutines and distributes b.N iterations among them.
739 // The number of goroutines defaults to GOMAXPROCS. To increase parallelism for
740 // non-CPU-bound benchmarks, call SetParallelism before RunParallel.
741 // RunParallel is usually used with the go test -cpu flag.
743 // The body function will be run in each goroutine. It should set up any
744 // goroutine-local state and then iterate until pb.Next returns false.
745 // It should not use the StartTimer, StopTimer, or ResetTimer functions,
746 // because they have global effect. It should also not call Run.
747 func (b *B) RunParallel(body func(*PB)) {
749 return // Nothing to do when probing.
751 // Calculate grain size as number of iterations that take ~100µs.
752 // 100µs is enough to amortize the overhead and provide sufficient
753 // dynamic load balancing.
755 if b.previousN > 0 && b.previousDuration > 0 {
756 grain = 1e5 * uint64(b.previousN) / uint64(b.previousDuration)
761 // We expect the inner loop and function call to take at least 10ns,
762 // so do not do more than 100µs/10ns=1e4 iterations.
768 numProcs := b.parallelism * runtime.GOMAXPROCS(0)
769 var wg sync.WaitGroup
771 for p := 0; p < numProcs; p++ {
783 if n <= uint64(b.N) && !b.Failed() {
784 b.Fatal("RunParallel: body exited without pb.Next() == false")
788 // SetParallelism sets the number of goroutines used by RunParallel to p*GOMAXPROCS.
789 // There is usually no need to call SetParallelism for CPU-bound benchmarks.
790 // If p is less than 1, this call will have no effect.
791 func (b *B) SetParallelism(p int) {
797 // Benchmark benchmarks a single function. It is useful for creating
798 // custom benchmarks that do not use the "go test" command.
800 // If f depends on testing flags, then Init must be used to register
801 // those flags before calling Benchmark and before calling flag.Parse.
803 // If f calls Run, the result will be an estimate of running all its
804 // subbenchmarks that don't call Run in sequence in a single benchmark.
805 func Benchmark(f func(b *B)) BenchmarkResult {
808 signal: make(chan bool),
812 benchTime: benchTime,
820 type discard struct{}
822 func (discard) Write(b []byte) (n int, err error) { return len(b), nil }