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