github.com/rsc/go@v0.0.0-20150416155037-e040fd465409/src/testing/benchmark.go (about) 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 "os" 11 "runtime" 12 "sync" 13 "sync/atomic" 14 "time" 15 ) 16 17 var matchBenchmarks = flag.String("test.bench", "", "regular expression 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") 20 21 // Global lock to ensure only one benchmark runs at a time. 22 var benchmarkLock sync.Mutex 23 24 // Used for every benchmark for measuring memory. 25 var memStats runtime.MemStats 26 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 { 30 Name string 31 F func(b *B) 32 } 33 34 // B is a type passed to Benchmark functions to manage benchmark 35 // timing and to specify the number of iterations to run. 36 type B struct { 37 common 38 N int 39 previousN int // number of iterations in the previous run 40 previousDuration time.Duration // total duration of the previous run 41 benchmark InternalBenchmark 42 bytes int64 43 timerOn bool 44 showAllocResult bool 45 result BenchmarkResult 46 parallelism int // RunParallel creates parallelism*GOMAXPROCS goroutines 47 // The initial states of memStats.Mallocs and memStats.TotalAlloc. 48 startAllocs uint64 49 startBytes uint64 50 // The net total of this test after being run. 51 netAllocs uint64 52 netBytes uint64 53 } 54 55 // StartTimer starts timing a test. This function is called automatically 56 // before a benchmark starts, but it can also used to resume timing after 57 // a call to StopTimer. 58 func (b *B) StartTimer() { 59 if !b.timerOn { 60 runtime.ReadMemStats(&memStats) 61 b.startAllocs = memStats.Mallocs 62 b.startBytes = memStats.TotalAlloc 63 b.start = time.Now() 64 b.timerOn = true 65 } 66 } 67 68 // StopTimer stops timing a test. This can be used to pause the timer 69 // while performing complex initialization that you don't 70 // want to measure. 71 func (b *B) StopTimer() { 72 if b.timerOn { 73 b.duration += time.Now().Sub(b.start) 74 runtime.ReadMemStats(&memStats) 75 b.netAllocs += memStats.Mallocs - b.startAllocs 76 b.netBytes += memStats.TotalAlloc - b.startBytes 77 b.timerOn = false 78 } 79 } 80 81 // ResetTimer zeros the elapsed benchmark time and memory allocation counters. 82 // It does not affect whether the timer is running. 83 func (b *B) ResetTimer() { 84 if b.timerOn { 85 runtime.ReadMemStats(&memStats) 86 b.startAllocs = memStats.Mallocs 87 b.startBytes = memStats.TotalAlloc 88 b.start = time.Now() 89 } 90 b.duration = 0 91 b.netAllocs = 0 92 b.netBytes = 0 93 } 94 95 // SetBytes records the number of bytes processed in a single operation. 96 // If this is called, the benchmark will report ns/op and MB/s. 97 func (b *B) SetBytes(n int64) { b.bytes = n } 98 99 // ReportAllocs enables malloc statistics for this benchmark. 100 // It is equivalent to setting -test.benchmem, but it only affects the 101 // benchmark function that calls ReportAllocs. 102 func (b *B) ReportAllocs() { 103 b.showAllocResult = true 104 } 105 106 func (b *B) nsPerOp() int64 { 107 if b.N <= 0 { 108 return 0 109 } 110 return b.duration.Nanoseconds() / int64(b.N) 111 } 112 113 // runN runs a single benchmark for the specified number of iterations. 114 func (b *B) runN(n int) { 115 benchmarkLock.Lock() 116 defer benchmarkLock.Unlock() 117 // Try to get a comparable environment for each run 118 // by clearing garbage from previous runs. 119 runtime.GC() 120 b.N = n 121 b.parallelism = 1 122 b.ResetTimer() 123 b.StartTimer() 124 b.benchmark.F(b) 125 b.StopTimer() 126 b.previousN = n 127 b.previousDuration = b.duration 128 } 129 130 func min(x, y int) int { 131 if x > y { 132 return y 133 } 134 return x 135 } 136 137 func max(x, y int) int { 138 if x < y { 139 return y 140 } 141 return x 142 } 143 144 // roundDown10 rounds a number down to the nearest power of 10. 145 func roundDown10(n int) int { 146 var tens = 0 147 // tens = floor(log_10(n)) 148 for n >= 10 { 149 n = n / 10 150 tens++ 151 } 152 // result = 10^tens 153 result := 1 154 for i := 0; i < tens; i++ { 155 result *= 10 156 } 157 return result 158 } 159 160 // roundUp rounds x up to a number of the form [1eX, 2eX, 3eX, 5eX]. 161 func roundUp(n int) int { 162 base := roundDown10(n) 163 switch { 164 case n <= base: 165 return base 166 case n <= (2 * base): 167 return 2 * base 168 case n <= (3 * base): 169 return 3 * base 170 case n <= (5 * base): 171 return 5 * base 172 default: 173 return 10 * base 174 } 175 } 176 177 // run times the benchmark function in a separate goroutine. 178 func (b *B) run() BenchmarkResult { 179 go b.launch() 180 <-b.signal 181 return b.result 182 } 183 184 // launch launches the benchmark function. It gradually increases the number 185 // of benchmark iterations until the benchmark runs for the requested benchtime. 186 // It prints timing information in this form 187 // testing.BenchmarkHello 100000 19 ns/op 188 // launch is run by the run function as a separate goroutine. 189 func (b *B) launch() { 190 // Run the benchmark for a single iteration in case it's expensive. 191 n := 1 192 193 // Signal that we're done whether we return normally 194 // or by FailNow's runtime.Goexit. 195 defer func() { 196 b.signal <- b 197 }() 198 199 b.runN(n) 200 // Run the benchmark for at least the specified amount of time. 201 d := *benchTime 202 for !b.failed && b.duration < d && n < 1e9 { 203 last := n 204 // Predict required iterations. 205 if b.nsPerOp() == 0 { 206 n = 1e9 207 } else { 208 n = int(d.Nanoseconds() / b.nsPerOp()) 209 } 210 // Run more iterations than we think we'll need (1.2x). 211 // Don't grow too fast in case we had timing errors previously. 212 // Be sure to run at least one more than last time. 213 n = max(min(n+n/5, 100*last), last+1) 214 // Round up to something easy to read. 215 n = roundUp(n) 216 b.runN(n) 217 } 218 b.result = BenchmarkResult{b.N, b.duration, b.bytes, b.netAllocs, b.netBytes} 219 } 220 221 // The results of a benchmark run. 222 type BenchmarkResult struct { 223 N int // The number of iterations. 224 T time.Duration // The total time taken. 225 Bytes int64 // Bytes processed in one iteration. 226 MemAllocs uint64 // The total number of memory allocations. 227 MemBytes uint64 // The total number of bytes allocated. 228 } 229 230 func (r BenchmarkResult) NsPerOp() int64 { 231 if r.N <= 0 { 232 return 0 233 } 234 return r.T.Nanoseconds() / int64(r.N) 235 } 236 237 func (r BenchmarkResult) mbPerSec() float64 { 238 if r.Bytes <= 0 || r.T <= 0 || r.N <= 0 { 239 return 0 240 } 241 return (float64(r.Bytes) * float64(r.N) / 1e6) / r.T.Seconds() 242 } 243 244 func (r BenchmarkResult) AllocsPerOp() int64 { 245 if r.N <= 0 { 246 return 0 247 } 248 return int64(r.MemAllocs) / int64(r.N) 249 } 250 251 func (r BenchmarkResult) AllocedBytesPerOp() int64 { 252 if r.N <= 0 { 253 return 0 254 } 255 return int64(r.MemBytes) / int64(r.N) 256 } 257 258 func (r BenchmarkResult) String() string { 259 mbs := r.mbPerSec() 260 mb := "" 261 if mbs != 0 { 262 mb = fmt.Sprintf("\t%7.2f MB/s", mbs) 263 } 264 nsop := r.NsPerOp() 265 ns := fmt.Sprintf("%10d ns/op", nsop) 266 if r.N > 0 && nsop < 100 { 267 // The format specifiers here make sure that 268 // the ones digits line up for all three possible formats. 269 if nsop < 10 { 270 ns = fmt.Sprintf("%13.2f ns/op", float64(r.T.Nanoseconds())/float64(r.N)) 271 } else { 272 ns = fmt.Sprintf("%12.1f ns/op", float64(r.T.Nanoseconds())/float64(r.N)) 273 } 274 } 275 return fmt.Sprintf("%8d\t%s%s", r.N, ns, mb) 276 } 277 278 func (r BenchmarkResult) MemString() string { 279 return fmt.Sprintf("%8d B/op\t%8d allocs/op", 280 r.AllocedBytesPerOp(), r.AllocsPerOp()) 281 } 282 283 // benchmarkName returns full name of benchmark including procs suffix. 284 func benchmarkName(name string, n int) string { 285 if n != 1 { 286 return fmt.Sprintf("%s-%d", name, n) 287 } 288 return name 289 } 290 291 // An internal function but exported because it is cross-package; part of the implementation 292 // of the "go test" command. 293 func RunBenchmarks(matchString func(pat, str string) (bool, error), benchmarks []InternalBenchmark) { 294 // If no flag was specified, don't run benchmarks. 295 if len(*matchBenchmarks) == 0 { 296 return 297 } 298 // Collect matching benchmarks and determine longest name. 299 maxprocs := 1 300 for _, procs := range cpuList { 301 if procs > maxprocs { 302 maxprocs = procs 303 } 304 } 305 maxlen := 0 306 var bs []InternalBenchmark 307 for _, Benchmark := range benchmarks { 308 matched, err := matchString(*matchBenchmarks, Benchmark.Name) 309 if err != nil { 310 fmt.Fprintf(os.Stderr, "testing: invalid regexp for -test.bench: %s\n", err) 311 os.Exit(1) 312 } 313 if matched { 314 bs = append(bs, Benchmark) 315 benchName := benchmarkName(Benchmark.Name, maxprocs) 316 if l := len(benchName); l > maxlen { 317 maxlen = l 318 } 319 } 320 } 321 for _, Benchmark := range bs { 322 for _, procs := range cpuList { 323 runtime.GOMAXPROCS(procs) 324 b := &B{ 325 common: common{ 326 signal: make(chan interface{}), 327 }, 328 benchmark: Benchmark, 329 } 330 benchName := benchmarkName(Benchmark.Name, procs) 331 fmt.Printf("%-*s\t", maxlen, benchName) 332 r := b.run() 333 if b.failed { 334 // The output could be very long here, but probably isn't. 335 // We print it all, regardless, because we don't want to trim the reason 336 // the benchmark failed. 337 fmt.Printf("--- FAIL: %s\n%s", benchName, b.output) 338 continue 339 } 340 results := r.String() 341 if *benchmarkMemory || b.showAllocResult { 342 results += "\t" + r.MemString() 343 } 344 fmt.Println(results) 345 // Unlike with tests, we ignore the -chatty flag and always print output for 346 // benchmarks since the output generation time will skew the results. 347 if len(b.output) > 0 { 348 b.trimOutput() 349 fmt.Printf("--- BENCH: %s\n%s", benchName, b.output) 350 } 351 if p := runtime.GOMAXPROCS(-1); p != procs { 352 fmt.Fprintf(os.Stderr, "testing: %s left GOMAXPROCS set to %d\n", benchName, p) 353 } 354 } 355 } 356 } 357 358 // trimOutput shortens the output from a benchmark, which can be very long. 359 func (b *B) trimOutput() { 360 // The output is likely to appear multiple times because the benchmark 361 // is run multiple times, but at least it will be seen. This is not a big deal 362 // because benchmarks rarely print, but just in case, we trim it if it's too long. 363 const maxNewlines = 10 364 for nlCount, j := 0, 0; j < len(b.output); j++ { 365 if b.output[j] == '\n' { 366 nlCount++ 367 if nlCount >= maxNewlines { 368 b.output = append(b.output[:j], "\n\t... [output truncated]\n"...) 369 break 370 } 371 } 372 } 373 } 374 375 // A PB is used by RunParallel for running parallel benchmarks. 376 type PB struct { 377 globalN *uint64 // shared between all worker goroutines iteration counter 378 grain uint64 // acquire that many iterations from globalN at once 379 cache uint64 // local cache of acquired iterations 380 bN uint64 // total number of iterations to execute (b.N) 381 } 382 383 // Next reports whether there are more iterations to execute. 384 func (pb *PB) Next() bool { 385 if pb.cache == 0 { 386 n := atomic.AddUint64(pb.globalN, pb.grain) 387 if n <= pb.bN { 388 pb.cache = pb.grain 389 } else if n < pb.bN+pb.grain { 390 pb.cache = pb.bN + pb.grain - n 391 } else { 392 return false 393 } 394 } 395 pb.cache-- 396 return true 397 } 398 399 // RunParallel runs a benchmark in parallel. 400 // It creates multiple goroutines and distributes b.N iterations among them. 401 // The number of goroutines defaults to GOMAXPROCS. To increase parallelism for 402 // non-CPU-bound benchmarks, call SetParallelism before RunParallel. 403 // RunParallel is usually used with the go test -cpu flag. 404 // 405 // The body function will be run in each goroutine. It should set up any 406 // goroutine-local state and then iterate until pb.Next returns false. 407 // It should not use the StartTimer, StopTimer, or ResetTimer functions, 408 // because they have global effect. 409 func (b *B) RunParallel(body func(*PB)) { 410 // Calculate grain size as number of iterations that take ~100µs. 411 // 100µs is enough to amortize the overhead and provide sufficient 412 // dynamic load balancing. 413 grain := uint64(0) 414 if b.previousN > 0 && b.previousDuration > 0 { 415 grain = 1e5 * uint64(b.previousN) / uint64(b.previousDuration) 416 } 417 if grain < 1 { 418 grain = 1 419 } 420 // We expect the inner loop and function call to take at least 10ns, 421 // so do not do more than 100µs/10ns=1e4 iterations. 422 if grain > 1e4 { 423 grain = 1e4 424 } 425 426 n := uint64(0) 427 numProcs := b.parallelism * runtime.GOMAXPROCS(0) 428 var wg sync.WaitGroup 429 wg.Add(numProcs) 430 for p := 0; p < numProcs; p++ { 431 go func() { 432 defer wg.Done() 433 pb := &PB{ 434 globalN: &n, 435 grain: grain, 436 bN: uint64(b.N), 437 } 438 body(pb) 439 }() 440 } 441 wg.Wait() 442 if n <= uint64(b.N) && !b.Failed() { 443 b.Fatal("RunParallel: body exited without pb.Next() == false") 444 } 445 } 446 447 // SetParallelism sets the number of goroutines used by RunParallel to p*GOMAXPROCS. 448 // There is usually no need to call SetParallelism for CPU-bound benchmarks. 449 // If p is less than 1, this call will have no effect. 450 func (b *B) SetParallelism(p int) { 451 if p >= 1 { 452 b.parallelism = p 453 } 454 } 455 456 // Benchmark benchmarks a single function. Useful for creating 457 // custom benchmarks that do not use the "go test" command. 458 func Benchmark(f func(b *B)) BenchmarkResult { 459 b := &B{ 460 common: common{ 461 signal: make(chan interface{}), 462 }, 463 benchmark: InternalBenchmark{"", f}, 464 } 465 return b.run() 466 }