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.
17 var matchBenchmarks = flag.String("test.bench", "", "regular expression per path component to select benchmarks to run")
18 var benchTime = flag.Duration("test.benchtime", 1*time.Second, "approximate run time for each benchmark")
19 var benchmarkMemory = flag.Bool("test.benchmem", false, "print memory allocations for benchmarks")
21 // Global lock to ensure only one benchmark runs at a time.
22 var benchmarkLock sync.Mutex
24 // Used for every benchmark for measuring memory.
25 var memStats runtime.MemStats
27 // An internal type but exported because it is cross-package; part of the implementation
28 // of the "go test" command.
29 type InternalBenchmark struct {
34 // B is a type passed to Benchmark functions to manage benchmark
35 // timing and to specify the number of iterations to run.
37 // A benchmark ends when its Benchmark function returns or calls any of the methods
38 // FailNow, Fatal, Fatalf, SkipNow, Skip, or Skipf. Those methods must be called
39 // only from the goroutine running the Benchmark function.
40 // The other reporting methods, such as the variations of Log and Error,
41 // may be called simultaneously from multiple goroutines.
43 // Like in tests, benchmark logs are accumulated during execution
44 // and dumped to standard error when done. Unlike in tests, benchmark logs
45 // are always printed, so as not to hide output whose existence may be
46 // affecting benchmark results.
51 previousN int // number of iterations in the previous run
52 previousDuration time.Duration // total duration of the previous run
54 benchTime time.Duration
56 missingBytes bool // one of the subbenchmarks does not have bytes set.
60 result BenchmarkResult
61 parallelism int // RunParallel creates parallelism*GOMAXPROCS goroutines
62 // The initial states of memStats.Mallocs and memStats.TotalAlloc.
65 // The net total of this test after being run.
70 // StartTimer starts timing a test. This function is called automatically
71 // before a benchmark starts, but it can also used to resume timing after
72 // a call to StopTimer.
73 func (b *B) StartTimer() {
75 runtime.ReadMemStats(&memStats)
76 b.startAllocs = memStats.Mallocs
77 b.startBytes = memStats.TotalAlloc
83 // StopTimer stops timing a test. This can be used to pause the timer
84 // while performing complex initialization that you don't
86 func (b *B) StopTimer() {
88 b.duration += time.Now().Sub(b.start)
89 runtime.ReadMemStats(&memStats)
90 b.netAllocs += memStats.Mallocs - b.startAllocs
91 b.netBytes += memStats.TotalAlloc - b.startBytes
96 // ResetTimer zeros the elapsed benchmark time and memory allocation counters.
97 // It does not affect whether the timer is running.
98 func (b *B) ResetTimer() {
100 runtime.ReadMemStats(&memStats)
101 b.startAllocs = memStats.Mallocs
102 b.startBytes = memStats.TotalAlloc
110 // SetBytes records the number of bytes processed in a single operation.
111 // If this is called, the benchmark will report ns/op and MB/s.
112 func (b *B) SetBytes(n int64) { b.bytes = n }
114 // ReportAllocs enables malloc statistics for this benchmark.
115 // It is equivalent to setting -test.benchmem, but it only affects the
116 // benchmark function that calls ReportAllocs.
117 func (b *B) ReportAllocs() {
118 b.showAllocResult = true
121 func (b *B) nsPerOp() int64 {
125 return b.duration.Nanoseconds() / int64(b.N)
128 // runN runs a single benchmark for the specified number of iterations.
129 func (b *B) runN(n int) {
131 defer benchmarkLock.Unlock()
132 // Try to get a comparable environment for each run
133 // by clearing garbage from previous runs.
142 b.previousDuration = b.duration
145 func min(x, y int) int {
152 func max(x, y int) int {
159 // roundDown10 rounds a number down to the nearest power of 10.
160 func roundDown10(n int) int {
162 // tens = floor(log_10(n))
169 for i := 0; i < tens; i++ {
175 // roundUp rounds x up to a number of the form [1eX, 2eX, 3eX, 5eX].
176 func roundUp(n int) int {
177 base := roundDown10(n)
181 case n <= (2 * base):
183 case n <= (3 * base):
185 case n <= (5 * base):
192 // run1 runs the first iteration of benchFunc. It returns whether more
193 // iterations of this benchmarks should be run.
194 func (b *B) run1() bool {
195 if ctx := b.context; ctx != nil {
196 // Extend maxLen, if needed.
197 if n := len(b.name) + ctx.extLen + 1; n > ctx.maxLen {
198 ctx.maxLen = n + 8 // Add additional slack to avoid too many jumps in size.
202 // Signal that we're done whether we return normally
203 // or by FailNow's runtime.Goexit.
212 fmt.Fprintf(b.w, "--- FAIL: %s\n%s", b.name, b.output)
215 // Only print the output if we know we are not going to proceed.
216 // Otherwise it is printed in processBench.
217 if b.hasSub || b.finished {
222 if b.chatty && (len(b.output) > 0 || b.finished) {
224 fmt.Fprintf(b.w, "--- %s: %s\n%s", tag, b.name, b.output)
231 // run executes the benchmark in a separate goroutine, including all of its
232 // subbenchmarks. b must not have subbenchmarks.
233 func (b *B) run() BenchmarkResult {
234 if b.context != nil {
235 // Running go test --test.bench
236 b.context.processBench(b) // Must call doBench.
238 // Running func Benchmark.
244 func (b *B) doBench() BenchmarkResult {
250 // launch launches the benchmark function. It gradually increases the number
251 // of benchmark iterations until the benchmark runs for the requested benchtime.
252 // launch is run by the doBench function as a separate goroutine.
253 // run1 must have been called on b.
254 func (b *B) launch() {
255 // Signal that we're done whether we return normally
256 // or by FailNow's runtime.Goexit.
261 // Run the benchmark for at least the specified amount of time.
263 for n := 1; !b.failed && b.duration < d && n < 1e9; {
265 // Predict required iterations.
266 n = int(d.Nanoseconds())
267 if nsop := b.nsPerOp(); nsop != 0 {
270 // Run more iterations than we think we'll need (1.2x).
271 // Don't grow too fast in case we had timing errors previously.
272 // Be sure to run at least one more than last time.
273 n = max(min(n+n/5, 100*last), last+1)
274 // Round up to something easy to read.
278 b.result = BenchmarkResult{b.N, b.duration, b.bytes, b.netAllocs, b.netBytes}
281 // The results of a benchmark run.
282 type BenchmarkResult struct {
283 N int // The number of iterations.
284 T time.Duration // The total time taken.
285 Bytes int64 // Bytes processed in one iteration.
286 MemAllocs uint64 // The total number of memory allocations.
287 MemBytes uint64 // The total number of bytes allocated.
290 func (r BenchmarkResult) NsPerOp() int64 {
294 return r.T.Nanoseconds() / int64(r.N)
297 func (r BenchmarkResult) mbPerSec() float64 {
298 if r.Bytes <= 0 || r.T <= 0 || r.N <= 0 {
301 return (float64(r.Bytes) * float64(r.N) / 1e6) / r.T.Seconds()
304 func (r BenchmarkResult) AllocsPerOp() int64 {
308 return int64(r.MemAllocs) / int64(r.N)
311 func (r BenchmarkResult) AllocedBytesPerOp() int64 {
315 return int64(r.MemBytes) / int64(r.N)
318 func (r BenchmarkResult) String() string {
322 mb = fmt.Sprintf("\t%7.2f MB/s", mbs)
325 ns := fmt.Sprintf("%10d ns/op", nsop)
326 if r.N > 0 && nsop < 100 {
327 // The format specifiers here make sure that
328 // the ones digits line up for all three possible formats.
330 ns = fmt.Sprintf("%13.2f ns/op", float64(r.T.Nanoseconds())/float64(r.N))
332 ns = fmt.Sprintf("%12.1f ns/op", float64(r.T.Nanoseconds())/float64(r.N))
335 return fmt.Sprintf("%8d\t%s%s", r.N, ns, mb)
338 func (r BenchmarkResult) MemString() string {
339 return fmt.Sprintf("%8d B/op\t%8d allocs/op",
340 r.AllocedBytesPerOp(), r.AllocsPerOp())
343 // benchmarkName returns full name of benchmark including procs suffix.
344 func benchmarkName(name string, n int) string {
346 return fmt.Sprintf("%s-%d", name, n)
351 type benchContext struct {
354 maxLen int // The largest recorded benchmark name.
355 extLen int // Maximum extension length.
358 // An internal function but exported because it is cross-package; part of the implementation
359 // of the "go test" command.
360 func RunBenchmarks(matchString func(pat, str string) (bool, error), benchmarks []InternalBenchmark) {
361 runBenchmarksInternal(matchString, benchmarks)
364 func runBenchmarksInternal(matchString func(pat, str string) (bool, error), benchmarks []InternalBenchmark) bool {
365 // If no flag was specified, don't run benchmarks.
366 if len(*matchBenchmarks) == 0 {
369 // Collect matching benchmarks and determine longest name.
371 for _, procs := range cpuList {
372 if procs > maxprocs {
376 ctx := &benchContext{
377 match: newMatcher(matchString, *matchBenchmarks, "-test.bench"),
378 extLen: len(benchmarkName("", maxprocs)),
380 var bs []InternalBenchmark
381 for _, Benchmark := range benchmarks {
382 if _, matched := ctx.match.fullName(nil, Benchmark.Name); matched {
383 bs = append(bs, Benchmark)
384 benchName := benchmarkName(Benchmark.Name, maxprocs)
385 if l := len(benchName) + ctx.extLen + 1; l > ctx.maxLen {
396 benchFunc: func(b *B) {
397 for _, Benchmark := range bs {
398 b.Run(Benchmark.Name, Benchmark.F)
401 benchTime: *benchTime,
408 // processBench runs bench b for the configured CPU counts and prints the results.
409 func (ctx *benchContext) processBench(b *B) {
410 for i, procs := range cpuList {
411 runtime.GOMAXPROCS(procs)
412 benchName := benchmarkName(b.name, procs)
413 fmt.Fprintf(b.w, "%-*s\t", ctx.maxLen, benchName)
414 // Recompute the running time for all but the first iteration.
418 signal: make(chan bool),
423 benchFunc: b.benchFunc,
424 benchTime: b.benchTime,
430 // The output could be very long here, but probably isn't.
431 // We print it all, regardless, because we don't want to trim the reason
432 // the benchmark failed.
433 fmt.Fprintf(b.w, "--- FAIL: %s\n%s", benchName, b.output)
436 results := r.String()
437 if *benchmarkMemory || b.showAllocResult {
438 results += "\t" + r.MemString()
440 fmt.Fprintln(b.w, results)
441 // Unlike with tests, we ignore the -chatty flag and always print output for
442 // benchmarks since the output generation time will skew the results.
443 if len(b.output) > 0 {
445 fmt.Fprintf(b.w, "--- BENCH: %s\n%s", benchName, b.output)
447 if p := runtime.GOMAXPROCS(-1); p != procs {
448 fmt.Fprintf(os.Stderr, "testing: %s left GOMAXPROCS set to %d\n", benchName, p)
453 // Run benchmarks f as a subbenchmark with the given name. It reports
454 // whether there were any failures.
456 // A subbenchmark is like any other benchmark. A benchmark that calls Run at
457 // least once will not be measured itself and will be called once with N=1.
458 func (b *B) Run(name string, f func(b *B)) bool {
459 // Since b has subbenchmarks, we will no longer run it as a benchmark itself.
460 // Release the lock and acquire it on exit to ensure locks stay paired.
462 benchmarkLock.Unlock()
463 defer benchmarkLock.Lock()
465 benchName, ok := b.name, true
466 if b.context != nil {
467 benchName, ok = b.context.match.fullName(&b.common, name)
474 signal: make(chan bool),
482 benchTime: b.benchTime,
492 // add simulates running benchmarks in sequence in a single iteration. It is
493 // used to give some meaningful results in case func Benchmark is used in
494 // combination with Run.
495 func (b *B) add(other BenchmarkResult) {
497 // The aggregated BenchmarkResults resemble running all subbenchmarks as
498 // in sequence in a single benchmark.
500 r.T += time.Duration(other.NsPerOp())
501 if other.Bytes == 0 {
502 // Summing Bytes is meaningless in aggregate if not all subbenchmarks
504 b.missingBytes = true
508 r.Bytes += other.Bytes
510 r.MemAllocs += uint64(other.AllocsPerOp())
511 r.MemBytes += uint64(other.AllocedBytesPerOp())
514 // trimOutput shortens the output from a benchmark, which can be very long.
515 func (b *B) trimOutput() {
516 // The output is likely to appear multiple times because the benchmark
517 // is run multiple times, but at least it will be seen. This is not a big deal
518 // because benchmarks rarely print, but just in case, we trim it if it's too long.
519 const maxNewlines = 10
520 for nlCount, j := 0, 0; j < len(b.output); j++ {
521 if b.output[j] == '\n' {
523 if nlCount >= maxNewlines {
524 b.output = append(b.output[:j], "\n\t... [output truncated]\n"...)
531 // A PB is used by RunParallel for running parallel benchmarks.
533 globalN *uint64 // shared between all worker goroutines iteration counter
534 grain uint64 // acquire that many iterations from globalN at once
535 cache uint64 // local cache of acquired iterations
536 bN uint64 // total number of iterations to execute (b.N)
539 // Next reports whether there are more iterations to execute.
540 func (pb *PB) Next() bool {
542 n := atomic.AddUint64(pb.globalN, pb.grain)
545 } else if n < pb.bN+pb.grain {
546 pb.cache = pb.bN + pb.grain - n
555 // RunParallel runs a benchmark in parallel.
556 // It creates multiple goroutines and distributes b.N iterations among them.
557 // The number of goroutines defaults to GOMAXPROCS. To increase parallelism for
558 // non-CPU-bound benchmarks, call SetParallelism before RunParallel.
559 // RunParallel is usually used with the go test -cpu flag.
561 // The body function will be run in each goroutine. It should set up any
562 // goroutine-local state and then iterate until pb.Next returns false.
563 // It should not use the StartTimer, StopTimer, or ResetTimer functions,
564 // because they have global effect. It should also not call Run.
565 func (b *B) RunParallel(body func(*PB)) {
567 return // Nothing to do when probing.
569 // Calculate grain size as number of iterations that take ~100µs.
570 // 100µs is enough to amortize the overhead and provide sufficient
571 // dynamic load balancing.
573 if b.previousN > 0 && b.previousDuration > 0 {
574 grain = 1e5 * uint64(b.previousN) / uint64(b.previousDuration)
579 // We expect the inner loop and function call to take at least 10ns,
580 // so do not do more than 100µs/10ns=1e4 iterations.
586 numProcs := b.parallelism * runtime.GOMAXPROCS(0)
587 var wg sync.WaitGroup
589 for p := 0; p < numProcs; p++ {
601 if n <= uint64(b.N) && !b.Failed() {
602 b.Fatal("RunParallel: body exited without pb.Next() == false")
606 // SetParallelism sets the number of goroutines used by RunParallel to p*GOMAXPROCS.
607 // There is usually no need to call SetParallelism for CPU-bound benchmarks.
608 // If p is less than 1, this call will have no effect.
609 func (b *B) SetParallelism(p int) {
615 // Benchmark benchmarks a single function. Useful for creating
616 // custom benchmarks that do not use the "go test" command.
618 // If f calls Run, the result will be an estimate of running all its
619 // subbenchmarks that don't call Run in sequence in a single benchmark.
620 func Benchmark(f func(b *B)) BenchmarkResult {
623 signal: make(chan bool),
627 benchTime: *benchTime,
630 return BenchmarkResult{}
635 type discard struct{}
637 func (discard) Write(b []byte) (n int, err error) { return len(b), nil }