github.com/rakyll/go@v0.0.0-20170216000551-64c02460d703/src/runtime/pprof/pprof.go (about) 1 // Copyright 2010 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 pprof writes runtime profiling data in the format expected 6 // by the pprof visualization tool. 7 // 8 // Profiling a Go program 9 // 10 // The first step to profiling a Go program is to enable profiling. 11 // Support for profiling benchmarks built with the standard testing 12 // package is built into go test. For example, the following command 13 // runs benchmarks in the current directory and writes the CPU and 14 // memory profiles to cpu.prof and mem.prof: 15 // 16 // go test -cpuprofile cpu.prof -memprofile mem.prof -bench . 17 // 18 // To add equivalent profiling support to a standalone program, add 19 // code like the following to your main function: 20 // 21 // var cpuprofile = flag.String("cpuprofile", "", "write cpu profile `file`") 22 // var memprofile = flag.String("memprofile", "", "write memory profile to `file`") 23 // 24 // func main() { 25 // flag.Parse() 26 // if *cpuprofile != "" { 27 // f, err := os.Create(*cpuprofile) 28 // if err != nil { 29 // log.Fatal("could not create CPU profile: ", err) 30 // } 31 // if err := pprof.StartCPUProfile(f); err != nil { 32 // log.Fatal("could not start CPU profile: ", err) 33 // } 34 // defer pprof.StopCPUProfile() 35 // } 36 // 37 // // ... rest of the program ... 38 // 39 // if *memprofile != "" { 40 // f, err := os.Create(*memprofile) 41 // if err != nil { 42 // log.Fatal("could not create memory profile: ", err) 43 // } 44 // runtime.GC() // get up-to-date statistics 45 // if err := pprof.WriteHeapProfile(f); err != nil { 46 // log.Fatal("could not write memory profile: ", err) 47 // } 48 // f.Close() 49 // } 50 // } 51 // 52 // There is also a standard HTTP interface to profiling data. Adding 53 // the following line will install handlers under the /debug/pprof/ 54 // URL to download live profiles: 55 // 56 // import _ "net/http/pprof" 57 // 58 // See the net/http/pprof package for more details. 59 // 60 // Profiles can then be visualized with the pprof tool: 61 // 62 // go tool pprof cpu.prof 63 // 64 // There are many commands available from the pprof command line. 65 // Commonly used commands include "top", which prints a summary of the 66 // top program hot-spots, and "web", which opens an interactive graph 67 // of hot-spots and their call graphs. Use "help" for information on 68 // all pprof commands. 69 // 70 // For more information about pprof, see 71 // https://github.com/google/pprof/blob/master/doc/pprof.md. 72 package pprof 73 74 import ( 75 "bufio" 76 "bytes" 77 "fmt" 78 "internal/pprof/profile" 79 "io" 80 "runtime" 81 "sort" 82 "strings" 83 "sync" 84 "text/tabwriter" 85 "time" 86 ) 87 88 // BUG(rsc): Profiles are only as good as the kernel support used to generate them. 89 // See https://golang.org/issue/13841 for details about known problems. 90 91 // A Profile is a collection of stack traces showing the call sequences 92 // that led to instances of a particular event, such as allocation. 93 // Packages can create and maintain their own profiles; the most common 94 // use is for tracking resources that must be explicitly closed, such as files 95 // or network connections. 96 // 97 // A Profile's methods can be called from multiple goroutines simultaneously. 98 // 99 // Each Profile has a unique name. A few profiles are predefined: 100 // 101 // goroutine - stack traces of all current goroutines 102 // heap - a sampling of all heap allocations 103 // threadcreate - stack traces that led to the creation of new OS threads 104 // block - stack traces that led to blocking on synchronization primitives 105 // mutex - stack traces of holders of contended mutexes 106 // 107 // These predefined profiles maintain themselves and panic on an explicit 108 // Add or Remove method call. 109 // 110 // The heap profile reports statistics as of the most recently completed 111 // garbage collection; it elides more recent allocation to avoid skewing 112 // the profile away from live data and toward garbage. 113 // If there has been no garbage collection at all, the heap profile reports 114 // all known allocations. This exception helps mainly in programs running 115 // without garbage collection enabled, usually for debugging purposes. 116 // 117 // The CPU profile is not available as a Profile. It has a special API, 118 // the StartCPUProfile and StopCPUProfile functions, because it streams 119 // output to a writer during profiling. 120 // 121 type Profile struct { 122 name string 123 mu sync.Mutex 124 m map[interface{}][]uintptr 125 count func() int 126 write func(io.Writer, int) error 127 } 128 129 // profiles records all registered profiles. 130 var profiles struct { 131 mu sync.Mutex 132 m map[string]*Profile 133 } 134 135 var goroutineProfile = &Profile{ 136 name: "goroutine", 137 count: countGoroutine, 138 write: writeGoroutine, 139 } 140 141 var threadcreateProfile = &Profile{ 142 name: "threadcreate", 143 count: countThreadCreate, 144 write: writeThreadCreate, 145 } 146 147 var heapProfile = &Profile{ 148 name: "heap", 149 count: countHeap, 150 write: writeHeap, 151 } 152 153 var blockProfile = &Profile{ 154 name: "block", 155 count: countBlock, 156 write: writeBlock, 157 } 158 159 var mutexProfile = &Profile{ 160 name: "mutex", 161 count: countMutex, 162 write: writeMutex, 163 } 164 165 func lockProfiles() { 166 profiles.mu.Lock() 167 if profiles.m == nil { 168 // Initial built-in profiles. 169 profiles.m = map[string]*Profile{ 170 "goroutine": goroutineProfile, 171 "threadcreate": threadcreateProfile, 172 "heap": heapProfile, 173 "block": blockProfile, 174 "mutex": mutexProfile, 175 } 176 } 177 } 178 179 func unlockProfiles() { 180 profiles.mu.Unlock() 181 } 182 183 // NewProfile creates a new profile with the given name. 184 // If a profile with that name already exists, NewProfile panics. 185 // The convention is to use a 'import/path.' prefix to create 186 // separate name spaces for each package. 187 // For compatibility with various tools that read pprof data, 188 // profile names should not contain spaces. 189 func NewProfile(name string) *Profile { 190 lockProfiles() 191 defer unlockProfiles() 192 if name == "" { 193 panic("pprof: NewProfile with empty name") 194 } 195 if profiles.m[name] != nil { 196 panic("pprof: NewProfile name already in use: " + name) 197 } 198 p := &Profile{ 199 name: name, 200 m: map[interface{}][]uintptr{}, 201 } 202 profiles.m[name] = p 203 return p 204 } 205 206 // Lookup returns the profile with the given name, or nil if no such profile exists. 207 func Lookup(name string) *Profile { 208 lockProfiles() 209 defer unlockProfiles() 210 return profiles.m[name] 211 } 212 213 // Profiles returns a slice of all the known profiles, sorted by name. 214 func Profiles() []*Profile { 215 lockProfiles() 216 defer unlockProfiles() 217 218 all := make([]*Profile, 0, len(profiles.m)) 219 for _, p := range profiles.m { 220 all = append(all, p) 221 } 222 223 sort.Slice(all, func(i, j int) bool { return all[i].name < all[j].name }) 224 return all 225 } 226 227 // Name returns this profile's name, which can be passed to Lookup to reobtain the profile. 228 func (p *Profile) Name() string { 229 return p.name 230 } 231 232 // Count returns the number of execution stacks currently in the profile. 233 func (p *Profile) Count() int { 234 p.mu.Lock() 235 defer p.mu.Unlock() 236 if p.count != nil { 237 return p.count() 238 } 239 return len(p.m) 240 } 241 242 // Add adds the current execution stack to the profile, associated with value. 243 // Add stores value in an internal map, so value must be suitable for use as 244 // a map key and will not be garbage collected until the corresponding 245 // call to Remove. Add panics if the profile already contains a stack for value. 246 // 247 // The skip parameter has the same meaning as runtime.Caller's skip 248 // and controls where the stack trace begins. Passing skip=0 begins the 249 // trace in the function calling Add. For example, given this 250 // execution stack: 251 // 252 // Add 253 // called from rpc.NewClient 254 // called from mypkg.Run 255 // called from main.main 256 // 257 // Passing skip=0 begins the stack trace at the call to Add inside rpc.NewClient. 258 // Passing skip=1 begins the stack trace at the call to NewClient inside mypkg.Run. 259 // 260 func (p *Profile) Add(value interface{}, skip int) { 261 if p.name == "" { 262 panic("pprof: use of uninitialized Profile") 263 } 264 if p.write != nil { 265 panic("pprof: Add called on built-in Profile " + p.name) 266 } 267 268 stk := make([]uintptr, 32) 269 n := runtime.Callers(skip+1, stk[:]) 270 271 p.mu.Lock() 272 defer p.mu.Unlock() 273 if p.m[value] != nil { 274 panic("pprof: Profile.Add of duplicate value") 275 } 276 p.m[value] = stk[:n] 277 } 278 279 // Remove removes the execution stack associated with value from the profile. 280 // It is a no-op if the value is not in the profile. 281 func (p *Profile) Remove(value interface{}) { 282 p.mu.Lock() 283 defer p.mu.Unlock() 284 delete(p.m, value) 285 } 286 287 // WriteTo writes a pprof-formatted snapshot of the profile to w. 288 // If a write to w returns an error, WriteTo returns that error. 289 // Otherwise, WriteTo returns nil. 290 // 291 // The debug parameter enables additional output. 292 // Passing debug=0 prints only the hexadecimal addresses that pprof needs. 293 // Passing debug=1 adds comments translating addresses to function names 294 // and line numbers, so that a programmer can read the profile without tools. 295 // 296 // The predefined profiles may assign meaning to other debug values; 297 // for example, when printing the "goroutine" profile, debug=2 means to 298 // print the goroutine stacks in the same form that a Go program uses 299 // when dying due to an unrecovered panic. 300 func (p *Profile) WriteTo(w io.Writer, debug int) error { 301 if p.name == "" { 302 panic("pprof: use of zero Profile") 303 } 304 if p.write != nil { 305 return p.write(w, debug) 306 } 307 308 // Obtain consistent snapshot under lock; then process without lock. 309 all := make([][]uintptr, 0, len(p.m)) 310 p.mu.Lock() 311 for _, stk := range p.m { 312 all = append(all, stk) 313 } 314 p.mu.Unlock() 315 316 // Map order is non-deterministic; make output deterministic. 317 sort.Sort(stackProfile(all)) 318 319 return printCountProfile(w, debug, p.name, stackProfile(all)) 320 } 321 322 type stackProfile [][]uintptr 323 324 func (x stackProfile) Len() int { return len(x) } 325 func (x stackProfile) Stack(i int) []uintptr { return x[i] } 326 func (x stackProfile) Swap(i, j int) { x[i], x[j] = x[j], x[i] } 327 func (x stackProfile) Less(i, j int) bool { 328 t, u := x[i], x[j] 329 for k := 0; k < len(t) && k < len(u); k++ { 330 if t[k] != u[k] { 331 return t[k] < u[k] 332 } 333 } 334 return len(t) < len(u) 335 } 336 337 // A countProfile is a set of stack traces to be printed as counts 338 // grouped by stack trace. There are multiple implementations: 339 // all that matters is that we can find out how many traces there are 340 // and obtain each trace in turn. 341 type countProfile interface { 342 Len() int 343 Stack(i int) []uintptr 344 } 345 346 // printCountProfile prints a countProfile at the specified debug level. 347 // The profile will be in compressed proto format unless debug is nonzero. 348 func printCountProfile(w io.Writer, debug int, name string, p countProfile) error { 349 // Build count of each stack. 350 var buf bytes.Buffer 351 key := func(stk []uintptr) string { 352 buf.Reset() 353 fmt.Fprintf(&buf, "@") 354 for _, pc := range stk { 355 fmt.Fprintf(&buf, " %#x", pc) 356 } 357 return buf.String() 358 } 359 count := map[string]int{} 360 index := map[string]int{} 361 var keys []string 362 n := p.Len() 363 for i := 0; i < n; i++ { 364 k := key(p.Stack(i)) 365 if count[k] == 0 { 366 index[k] = i 367 keys = append(keys, k) 368 } 369 count[k]++ 370 } 371 372 sort.Sort(&keysByCount{keys, count}) 373 374 if debug > 0 { 375 // Print debug profile in legacy format 376 tw := tabwriter.NewWriter(w, 1, 8, 1, '\t', 0) 377 fmt.Fprintf(tw, "%s profile: total %d\n", name, p.Len()) 378 for _, k := range keys { 379 fmt.Fprintf(tw, "%d %s\n", count[k], k) 380 printStackRecord(tw, p.Stack(index[k]), false) 381 } 382 return tw.Flush() 383 } 384 385 // Output profile in protobuf form. 386 prof := &profile.Profile{ 387 PeriodType: &profile.ValueType{Type: name, Unit: "count"}, 388 Period: 1, 389 Sample: make([]*profile.Sample, 0, len(keys)), 390 SampleType: []*profile.ValueType{{Type: name, Unit: "count"}}, 391 } 392 locMap := make(map[uintptr]*profile.Location) 393 for _, k := range keys { 394 stk := p.Stack(index[k]) 395 c := count[k] 396 locs := make([]*profile.Location, len(stk)) 397 for i, addr := range stk { 398 loc := locMap[addr] 399 if loc == nil { 400 loc = &profile.Location{ 401 ID: uint64(len(locMap) + 1), 402 Address: uint64(addr - 1), 403 } 404 prof.Location = append(prof.Location, loc) 405 locMap[addr] = loc 406 } 407 locs[i] = loc 408 } 409 prof.Sample = append(prof.Sample, &profile.Sample{ 410 Location: locs, 411 Value: []int64{int64(c)}, 412 }) 413 } 414 return prof.Write(w) 415 } 416 417 // keysByCount sorts keys with higher counts first, breaking ties by key string order. 418 type keysByCount struct { 419 keys []string 420 count map[string]int 421 } 422 423 func (x *keysByCount) Len() int { return len(x.keys) } 424 func (x *keysByCount) Swap(i, j int) { x.keys[i], x.keys[j] = x.keys[j], x.keys[i] } 425 func (x *keysByCount) Less(i, j int) bool { 426 ki, kj := x.keys[i], x.keys[j] 427 ci, cj := x.count[ki], x.count[kj] 428 if ci != cj { 429 return ci > cj 430 } 431 return ki < kj 432 } 433 434 // printStackRecord prints the function + source line information 435 // for a single stack trace. 436 func printStackRecord(w io.Writer, stk []uintptr, allFrames bool) { 437 show := allFrames 438 frames := runtime.CallersFrames(stk) 439 for { 440 frame, more := frames.Next() 441 name := frame.Function 442 if name == "" { 443 show = true 444 fmt.Fprintf(w, "#\t%#x\n", frame.PC) 445 } else if name != "runtime.goexit" && (show || !strings.HasPrefix(name, "runtime.")) { 446 // Hide runtime.goexit and any runtime functions at the beginning. 447 // This is useful mainly for allocation traces. 448 show = true 449 fmt.Fprintf(w, "#\t%#x\t%s+%#x\t%s:%d\n", frame.PC, name, frame.PC-frame.Entry, frame.File, frame.Line) 450 } 451 if !more { 452 break 453 } 454 } 455 if !show { 456 // We didn't print anything; do it again, 457 // and this time include runtime functions. 458 printStackRecord(w, stk, true) 459 return 460 } 461 fmt.Fprintf(w, "\n") 462 } 463 464 // Interface to system profiles. 465 466 // WriteHeapProfile is shorthand for Lookup("heap").WriteTo(w, 0). 467 // It is preserved for backwards compatibility. 468 func WriteHeapProfile(w io.Writer) error { 469 return writeHeap(w, 0) 470 } 471 472 // countHeap returns the number of records in the heap profile. 473 func countHeap() int { 474 n, _ := runtime.MemProfile(nil, true) 475 return n 476 } 477 478 // writeHeap writes the current runtime heap profile to w. 479 func writeHeap(w io.Writer, debug int) error { 480 // Find out how many records there are (MemProfile(nil, true)), 481 // allocate that many records, and get the data. 482 // There's a race—more records might be added between 483 // the two calls—so allocate a few extra records for safety 484 // and also try again if we're very unlucky. 485 // The loop should only execute one iteration in the common case. 486 var p []runtime.MemProfileRecord 487 n, ok := runtime.MemProfile(nil, true) 488 for { 489 // Allocate room for a slightly bigger profile, 490 // in case a few more entries have been added 491 // since the call to MemProfile. 492 p = make([]runtime.MemProfileRecord, n+50) 493 n, ok = runtime.MemProfile(p, true) 494 if ok { 495 p = p[0:n] 496 break 497 } 498 // Profile grew; try again. 499 } 500 501 if debug == 0 { 502 pp := encodeMemProfile(p, int64(runtime.MemProfileRate), time.Now()) 503 return pp.Write(w) 504 } 505 506 sort.Slice(p, func(i, j int) bool { return p[i].InUseBytes() > p[j].InUseBytes() }) 507 508 b := bufio.NewWriter(w) 509 tw := tabwriter.NewWriter(b, 1, 8, 1, '\t', 0) 510 w = tw 511 512 var total runtime.MemProfileRecord 513 for i := range p { 514 r := &p[i] 515 total.AllocBytes += r.AllocBytes 516 total.AllocObjects += r.AllocObjects 517 total.FreeBytes += r.FreeBytes 518 total.FreeObjects += r.FreeObjects 519 } 520 521 // Technically the rate is MemProfileRate not 2*MemProfileRate, 522 // but early versions of the C++ heap profiler reported 2*MemProfileRate, 523 // so that's what pprof has come to expect. 524 fmt.Fprintf(w, "heap profile: %d: %d [%d: %d] @ heap/%d\n", 525 total.InUseObjects(), total.InUseBytes(), 526 total.AllocObjects, total.AllocBytes, 527 2*runtime.MemProfileRate) 528 529 for i := range p { 530 r := &p[i] 531 fmt.Fprintf(w, "%d: %d [%d: %d] @", 532 r.InUseObjects(), r.InUseBytes(), 533 r.AllocObjects, r.AllocBytes) 534 for _, pc := range r.Stack() { 535 fmt.Fprintf(w, " %#x", pc) 536 } 537 fmt.Fprintf(w, "\n") 538 printStackRecord(w, r.Stack(), false) 539 } 540 541 // Print memstats information too. 542 // Pprof will ignore, but useful for people 543 s := new(runtime.MemStats) 544 runtime.ReadMemStats(s) 545 fmt.Fprintf(w, "\n# runtime.MemStats\n") 546 fmt.Fprintf(w, "# Alloc = %d\n", s.Alloc) 547 fmt.Fprintf(w, "# TotalAlloc = %d\n", s.TotalAlloc) 548 fmt.Fprintf(w, "# Sys = %d\n", s.Sys) 549 fmt.Fprintf(w, "# Lookups = %d\n", s.Lookups) 550 fmt.Fprintf(w, "# Mallocs = %d\n", s.Mallocs) 551 fmt.Fprintf(w, "# Frees = %d\n", s.Frees) 552 553 fmt.Fprintf(w, "# HeapAlloc = %d\n", s.HeapAlloc) 554 fmt.Fprintf(w, "# HeapSys = %d\n", s.HeapSys) 555 fmt.Fprintf(w, "# HeapIdle = %d\n", s.HeapIdle) 556 fmt.Fprintf(w, "# HeapInuse = %d\n", s.HeapInuse) 557 fmt.Fprintf(w, "# HeapReleased = %d\n", s.HeapReleased) 558 fmt.Fprintf(w, "# HeapObjects = %d\n", s.HeapObjects) 559 560 fmt.Fprintf(w, "# Stack = %d / %d\n", s.StackInuse, s.StackSys) 561 fmt.Fprintf(w, "# MSpan = %d / %d\n", s.MSpanInuse, s.MSpanSys) 562 fmt.Fprintf(w, "# MCache = %d / %d\n", s.MCacheInuse, s.MCacheSys) 563 fmt.Fprintf(w, "# BuckHashSys = %d\n", s.BuckHashSys) 564 fmt.Fprintf(w, "# GCSys = %d\n", s.GCSys) 565 fmt.Fprintf(w, "# OtherSys = %d\n", s.OtherSys) 566 567 fmt.Fprintf(w, "# NextGC = %d\n", s.NextGC) 568 fmt.Fprintf(w, "# LastGC = %d\n", s.LastGC) 569 fmt.Fprintf(w, "# PauseNs = %d\n", s.PauseNs) 570 fmt.Fprintf(w, "# PauseEnd = %d\n", s.PauseEnd) 571 fmt.Fprintf(w, "# NumGC = %d\n", s.NumGC) 572 fmt.Fprintf(w, "# NumForcedGC = %d\n", s.NumForcedGC) 573 fmt.Fprintf(w, "# GCCPUFraction = %v\n", s.GCCPUFraction) 574 fmt.Fprintf(w, "# DebugGC = %v\n", s.DebugGC) 575 576 tw.Flush() 577 return b.Flush() 578 } 579 580 // countThreadCreate returns the size of the current ThreadCreateProfile. 581 func countThreadCreate() int { 582 n, _ := runtime.ThreadCreateProfile(nil) 583 return n 584 } 585 586 // writeThreadCreate writes the current runtime ThreadCreateProfile to w. 587 func writeThreadCreate(w io.Writer, debug int) error { 588 return writeRuntimeProfile(w, debug, "threadcreate", runtime.ThreadCreateProfile) 589 } 590 591 // countGoroutine returns the number of goroutines. 592 func countGoroutine() int { 593 return runtime.NumGoroutine() 594 } 595 596 // writeGoroutine writes the current runtime GoroutineProfile to w. 597 func writeGoroutine(w io.Writer, debug int) error { 598 if debug >= 2 { 599 return writeGoroutineStacks(w) 600 } 601 return writeRuntimeProfile(w, debug, "goroutine", runtime.GoroutineProfile) 602 } 603 604 func writeGoroutineStacks(w io.Writer) error { 605 // We don't know how big the buffer needs to be to collect 606 // all the goroutines. Start with 1 MB and try a few times, doubling each time. 607 // Give up and use a truncated trace if 64 MB is not enough. 608 buf := make([]byte, 1<<20) 609 for i := 0; ; i++ { 610 n := runtime.Stack(buf, true) 611 if n < len(buf) { 612 buf = buf[:n] 613 break 614 } 615 if len(buf) >= 64<<20 { 616 // Filled 64 MB - stop there. 617 break 618 } 619 buf = make([]byte, 2*len(buf)) 620 } 621 _, err := w.Write(buf) 622 return err 623 } 624 625 func writeRuntimeProfile(w io.Writer, debug int, name string, fetch func([]runtime.StackRecord) (int, bool)) error { 626 // Find out how many records there are (fetch(nil)), 627 // allocate that many records, and get the data. 628 // There's a race—more records might be added between 629 // the two calls—so allocate a few extra records for safety 630 // and also try again if we're very unlucky. 631 // The loop should only execute one iteration in the common case. 632 var p []runtime.StackRecord 633 n, ok := fetch(nil) 634 for { 635 // Allocate room for a slightly bigger profile, 636 // in case a few more entries have been added 637 // since the call to ThreadProfile. 638 p = make([]runtime.StackRecord, n+10) 639 n, ok = fetch(p) 640 if ok { 641 p = p[0:n] 642 break 643 } 644 // Profile grew; try again. 645 } 646 647 return printCountProfile(w, debug, name, runtimeProfile(p)) 648 } 649 650 type runtimeProfile []runtime.StackRecord 651 652 func (p runtimeProfile) Len() int { return len(p) } 653 func (p runtimeProfile) Stack(i int) []uintptr { return p[i].Stack() } 654 655 var cpu struct { 656 sync.Mutex 657 profiling bool 658 done chan bool 659 } 660 661 // StartCPUProfile enables CPU profiling for the current process. 662 // While profiling, the profile will be buffered and written to w. 663 // StartCPUProfile returns an error if profiling is already enabled. 664 // 665 // On Unix-like systems, StartCPUProfile does not work by default for 666 // Go code built with -buildmode=c-archive or -buildmode=c-shared. 667 // StartCPUProfile relies on the SIGPROF signal, but that signal will 668 // be delivered to the main program's SIGPROF signal handler (if any) 669 // not to the one used by Go. To make it work, call os/signal.Notify 670 // for syscall.SIGPROF, but note that doing so may break any profiling 671 // being done by the main program. 672 func StartCPUProfile(w io.Writer) error { 673 // The runtime routines allow a variable profiling rate, 674 // but in practice operating systems cannot trigger signals 675 // at more than about 500 Hz, and our processing of the 676 // signal is not cheap (mostly getting the stack trace). 677 // 100 Hz is a reasonable choice: it is frequent enough to 678 // produce useful data, rare enough not to bog down the 679 // system, and a nice round number to make it easy to 680 // convert sample counts to seconds. Instead of requiring 681 // each client to specify the frequency, we hard code it. 682 const hz = 100 683 684 cpu.Lock() 685 defer cpu.Unlock() 686 if cpu.done == nil { 687 cpu.done = make(chan bool) 688 } 689 // Double-check. 690 if cpu.profiling { 691 return fmt.Errorf("cpu profiling already in use") 692 } 693 cpu.profiling = true 694 runtime.SetCPUProfileRate(hz) 695 go profileWriter(w) 696 return nil 697 } 698 699 func profileWriter(w io.Writer) { 700 startTime := time.Now() 701 // This will buffer the entire profile into buf and then 702 // translate it into a profile.Profile structure. This will 703 // create two copies of all the data in the profile in memory. 704 // TODO(matloob): Convert each chunk of the proto output and 705 // stream it out instead of converting the entire profile. 706 var buf bytes.Buffer 707 for { 708 data := runtime.CPUProfile() 709 if data == nil { 710 break 711 } 712 buf.Write(data) 713 } 714 715 profile, err := translateCPUProfile(buf.Bytes(), startTime) 716 if err != nil { 717 // The runtime should never produce an invalid or truncated profile. 718 // It drops records that can't fit into its log buffers. 719 panic(fmt.Errorf("could not translate binary profile to proto format: %v", err)) 720 } 721 722 profile.Write(w) 723 cpu.done <- true 724 } 725 726 // StopCPUProfile stops the current CPU profile, if any. 727 // StopCPUProfile only returns after all the writes for the 728 // profile have completed. 729 func StopCPUProfile() { 730 cpu.Lock() 731 defer cpu.Unlock() 732 733 if !cpu.profiling { 734 return 735 } 736 cpu.profiling = false 737 runtime.SetCPUProfileRate(0) 738 <-cpu.done 739 } 740 741 // countBlock returns the number of records in the blocking profile. 742 func countBlock() int { 743 n, _ := runtime.BlockProfile(nil) 744 return n 745 } 746 747 // countMutex returns the number of records in the mutex profile. 748 func countMutex() int { 749 n, _ := runtime.MutexProfile(nil) 750 return n 751 } 752 753 // writeBlock writes the current blocking profile to w. 754 func writeBlock(w io.Writer, debug int) error { 755 var p []runtime.BlockProfileRecord 756 n, ok := runtime.BlockProfile(nil) 757 for { 758 p = make([]runtime.BlockProfileRecord, n+50) 759 n, ok = runtime.BlockProfile(p) 760 if ok { 761 p = p[:n] 762 break 763 } 764 } 765 766 sort.Slice(p, func(i, j int) bool { return p[i].Cycles > p[j].Cycles }) 767 768 b := bufio.NewWriter(w) 769 var tw *tabwriter.Writer 770 w = b 771 if debug > 0 { 772 tw = tabwriter.NewWriter(w, 1, 8, 1, '\t', 0) 773 w = tw 774 } 775 776 fmt.Fprintf(w, "--- contention:\n") 777 fmt.Fprintf(w, "cycles/second=%v\n", runtime_cyclesPerSecond()) 778 for i := range p { 779 r := &p[i] 780 fmt.Fprintf(w, "%v %v @", r.Cycles, r.Count) 781 for _, pc := range r.Stack() { 782 fmt.Fprintf(w, " %#x", pc) 783 } 784 fmt.Fprint(w, "\n") 785 if debug > 0 { 786 printStackRecord(w, r.Stack(), true) 787 } 788 } 789 790 if tw != nil { 791 tw.Flush() 792 } 793 return b.Flush() 794 } 795 796 // writeMutex writes the current mutex profile to w. 797 func writeMutex(w io.Writer, debug int) error { 798 // TODO(pjw): too much common code with writeBlock. FIX! 799 var p []runtime.BlockProfileRecord 800 n, ok := runtime.MutexProfile(nil) 801 for { 802 p = make([]runtime.BlockProfileRecord, n+50) 803 n, ok = runtime.MutexProfile(p) 804 if ok { 805 p = p[:n] 806 break 807 } 808 } 809 810 sort.Slice(p, func(i, j int) bool { return p[i].Cycles > p[j].Cycles }) 811 812 b := bufio.NewWriter(w) 813 var tw *tabwriter.Writer 814 w = b 815 if debug > 0 { 816 tw = tabwriter.NewWriter(w, 1, 8, 1, '\t', 0) 817 w = tw 818 } 819 820 fmt.Fprintf(w, "--- mutex:\n") 821 fmt.Fprintf(w, "cycles/second=%v\n", runtime_cyclesPerSecond()) 822 fmt.Fprintf(w, "sampling period=%d\n", runtime.SetMutexProfileFraction(-1)) 823 for i := range p { 824 r := &p[i] 825 fmt.Fprintf(w, "%v %v @", r.Cycles, r.Count) 826 for _, pc := range r.Stack() { 827 fmt.Fprintf(w, " %#x", pc) 828 } 829 fmt.Fprint(w, "\n") 830 if debug > 0 { 831 printStackRecord(w, r.Stack(), true) 832 } 833 } 834 835 if tw != nil { 836 tw.Flush() 837 } 838 return b.Flush() 839 } 840 841 func runtime_cyclesPerSecond() int64