pprof.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  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. // Package pprof writes runtime profiling data in the format expected
  5. // by the pprof visualization tool.
  6. // For more information about pprof, see
  7. // http://code.google.com/p/google-perftools/.
  8. package pprof
  9. import (
  10. "bufio"
  11. "bytes"
  12. "fmt"
  13. "io"
  14. "runtime"
  15. "sort"
  16. "strings"
  17. "sync"
  18. "text/tabwriter"
  19. )
  20. // BUG(rsc): Profiles are incomplete and inaccurate on NetBSD and OS X.
  21. // See http://golang.org/issue/6047 for details.
  22. // A Profile is a collection of stack traces showing the call sequences
  23. // that led to instances of a particular event, such as allocation.
  24. // Packages can create and maintain their own profiles; the most common
  25. // use is for tracking resources that must be explicitly closed, such as files
  26. // or network connections.
  27. //
  28. // A Profile's methods can be called from multiple goroutines simultaneously.
  29. //
  30. // Each Profile has a unique name. A few profiles are predefined:
  31. //
  32. // goroutine - stack traces of all current goroutines
  33. // heap - a sampling of all heap allocations
  34. // threadcreate - stack traces that led to the creation of new OS threads
  35. // block - stack traces that led to blocking on synchronization primitives
  36. //
  37. // These predefined profiles maintain themselves and panic on an explicit
  38. // Add or Remove method call.
  39. //
  40. // The CPU profile is not available as a Profile. It has a special API,
  41. // the StartCPUProfile and StopCPUProfile functions, because it streams
  42. // output to a writer during profiling.
  43. //
  44. type Profile struct {
  45. name string
  46. mu sync.Mutex
  47. m map[interface{}][]uintptr
  48. count func() int
  49. write func(io.Writer, int) error
  50. }
  51. // profiles records all registered profiles.
  52. var profiles struct {
  53. mu sync.Mutex
  54. m map[string]*Profile
  55. }
  56. var goroutineProfile = &Profile{
  57. name: "goroutine",
  58. count: countGoroutine,
  59. write: writeGoroutine,
  60. }
  61. var threadcreateProfile = &Profile{
  62. name: "threadcreate",
  63. count: countThreadCreate,
  64. write: writeThreadCreate,
  65. }
  66. var heapProfile = &Profile{
  67. name: "heap",
  68. count: countHeap,
  69. write: writeHeap,
  70. }
  71. var blockProfile = &Profile{
  72. name: "block",
  73. count: countBlock,
  74. write: writeBlock,
  75. }
  76. func lockProfiles() {
  77. profiles.mu.Lock()
  78. if profiles.m == nil {
  79. // Initial built-in profiles.
  80. profiles.m = map[string]*Profile{
  81. "goroutine": goroutineProfile,
  82. "threadcreate": threadcreateProfile,
  83. "heap": heapProfile,
  84. "block": blockProfile,
  85. }
  86. }
  87. }
  88. func unlockProfiles() {
  89. profiles.mu.Unlock()
  90. }
  91. // NewProfile creates a new profile with the given name.
  92. // If a profile with that name already exists, NewProfile panics.
  93. // The convention is to use a 'import/path.' prefix to create
  94. // separate name spaces for each package.
  95. func NewProfile(name string) *Profile {
  96. lockProfiles()
  97. defer unlockProfiles()
  98. if name == "" {
  99. panic("pprof: NewProfile with empty name")
  100. }
  101. if profiles.m[name] != nil {
  102. panic("pprof: NewProfile name already in use: " + name)
  103. }
  104. p := &Profile{
  105. name: name,
  106. m: map[interface{}][]uintptr{},
  107. }
  108. profiles.m[name] = p
  109. return p
  110. }
  111. // Lookup returns the profile with the given name, or nil if no such profile exists.
  112. func Lookup(name string) *Profile {
  113. lockProfiles()
  114. defer unlockProfiles()
  115. return profiles.m[name]
  116. }
  117. // Profiles returns a slice of all the known profiles, sorted by name.
  118. func Profiles() []*Profile {
  119. lockProfiles()
  120. defer unlockProfiles()
  121. var all []*Profile
  122. for _, p := range profiles.m {
  123. all = append(all, p)
  124. }
  125. sort.Sort(byName(all))
  126. return all
  127. }
  128. type byName []*Profile
  129. func (x byName) Len() int { return len(x) }
  130. func (x byName) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
  131. func (x byName) Less(i, j int) bool { return x[i].name < x[j].name }
  132. // Name returns this profile's name, which can be passed to Lookup to reobtain the profile.
  133. func (p *Profile) Name() string {
  134. return p.name
  135. }
  136. // Count returns the number of execution stacks currently in the profile.
  137. func (p *Profile) Count() int {
  138. p.mu.Lock()
  139. defer p.mu.Unlock()
  140. if p.count != nil {
  141. return p.count()
  142. }
  143. return len(p.m)
  144. }
  145. // Add adds the current execution stack to the profile, associated with value.
  146. // Add stores value in an internal map, so value must be suitable for use as
  147. // a map key and will not be garbage collected until the corresponding
  148. // call to Remove. Add panics if the profile already contains a stack for value.
  149. //
  150. // The skip parameter has the same meaning as runtime.Caller's skip
  151. // and controls where the stack trace begins. Passing skip=0 begins the
  152. // trace in the function calling Add. For example, given this
  153. // execution stack:
  154. //
  155. // Add
  156. // called from rpc.NewClient
  157. // called from mypkg.Run
  158. // called from main.main
  159. //
  160. // Passing skip=0 begins the stack trace at the call to Add inside rpc.NewClient.
  161. // Passing skip=1 begins the stack trace at the call to NewClient inside mypkg.Run.
  162. //
  163. func (p *Profile) Add(value interface{}, skip int) {
  164. if p.name == "" {
  165. panic("pprof: use of uninitialized Profile")
  166. }
  167. if p.write != nil {
  168. panic("pprof: Add called on built-in Profile " + p.name)
  169. }
  170. stk := make([]uintptr, 32)
  171. n := runtime.Callers(skip+1, stk[:])
  172. p.mu.Lock()
  173. defer p.mu.Unlock()
  174. if p.m[value] != nil {
  175. panic("pprof: Profile.Add of duplicate value")
  176. }
  177. p.m[value] = stk[:n]
  178. }
  179. // Remove removes the execution stack associated with value from the profile.
  180. // It is a no-op if the value is not in the profile.
  181. func (p *Profile) Remove(value interface{}) {
  182. p.mu.Lock()
  183. defer p.mu.Unlock()
  184. delete(p.m, value)
  185. }
  186. // WriteTo writes a pprof-formatted snapshot of the profile to w.
  187. // If a write to w returns an error, WriteTo returns that error.
  188. // Otherwise, WriteTo returns nil.
  189. //
  190. // The debug parameter enables additional output.
  191. // Passing debug=0 prints only the hexadecimal addresses that pprof needs.
  192. // Passing debug=1 adds comments translating addresses to function names
  193. // and line numbers, so that a programmer can read the profile without tools.
  194. //
  195. // The predefined profiles may assign meaning to other debug values;
  196. // for example, when printing the "goroutine" profile, debug=2 means to
  197. // print the goroutine stacks in the same form that a Go program uses
  198. // when dying due to an unrecovered panic.
  199. func (p *Profile) WriteTo(w io.Writer, debug int) error {
  200. if p.name == "" {
  201. panic("pprof: use of zero Profile")
  202. }
  203. if p.write != nil {
  204. return p.write(w, debug)
  205. }
  206. // Obtain consistent snapshot under lock; then process without lock.
  207. var all [][]uintptr
  208. p.mu.Lock()
  209. for _, stk := range p.m {
  210. all = append(all, stk)
  211. }
  212. p.mu.Unlock()
  213. // Map order is non-deterministic; make output deterministic.
  214. sort.Sort(stackProfile(all))
  215. return printCountProfile(w, debug, p.name, stackProfile(all))
  216. }
  217. type stackProfile [][]uintptr
  218. func (x stackProfile) Len() int { return len(x) }
  219. func (x stackProfile) Stack(i int) []uintptr { return x[i] }
  220. func (x stackProfile) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
  221. func (x stackProfile) Less(i, j int) bool {
  222. t, u := x[i], x[j]
  223. for k := 0; k < len(t) && k < len(u); k++ {
  224. if t[k] != u[k] {
  225. return t[k] < u[k]
  226. }
  227. }
  228. return len(t) < len(u)
  229. }
  230. // A countProfile is a set of stack traces to be printed as counts
  231. // grouped by stack trace. There are multiple implementations:
  232. // all that matters is that we can find out how many traces there are
  233. // and obtain each trace in turn.
  234. type countProfile interface {
  235. Len() int
  236. Stack(i int) []uintptr
  237. }
  238. // printCountProfile prints a countProfile at the specified debug level.
  239. func printCountProfile(w io.Writer, debug int, name string, p countProfile) error {
  240. b := bufio.NewWriter(w)
  241. var tw *tabwriter.Writer
  242. w = b
  243. if debug > 0 {
  244. tw = tabwriter.NewWriter(w, 1, 8, 1, '\t', 0)
  245. w = tw
  246. }
  247. fmt.Fprintf(w, "%s profile: total %d\n", name, p.Len())
  248. // Build count of each stack.
  249. var buf bytes.Buffer
  250. key := func(stk []uintptr) string {
  251. buf.Reset()
  252. fmt.Fprintf(&buf, "@")
  253. for _, pc := range stk {
  254. fmt.Fprintf(&buf, " %#x", pc)
  255. }
  256. return buf.String()
  257. }
  258. m := map[string]int{}
  259. n := p.Len()
  260. for i := 0; i < n; i++ {
  261. m[key(p.Stack(i))]++
  262. }
  263. // Print stacks, listing count on first occurrence of a unique stack.
  264. for i := 0; i < n; i++ {
  265. stk := p.Stack(i)
  266. s := key(stk)
  267. if count := m[s]; count != 0 {
  268. fmt.Fprintf(w, "%d %s\n", count, s)
  269. if debug > 0 {
  270. printStackRecord(w, stk, false)
  271. }
  272. delete(m, s)
  273. }
  274. }
  275. if tw != nil {
  276. tw.Flush()
  277. }
  278. return b.Flush()
  279. }
  280. // printStackRecord prints the function + source line information
  281. // for a single stack trace.
  282. func printStackRecord(w io.Writer, stk []uintptr, allFrames bool) {
  283. show := allFrames
  284. wasPanic := false
  285. for i, pc := range stk {
  286. f := runtime.FuncForPC(pc)
  287. if f == nil {
  288. show = true
  289. fmt.Fprintf(w, "#\t%#x\n", pc)
  290. wasPanic = false
  291. } else {
  292. tracepc := pc
  293. // Back up to call instruction.
  294. if i > 0 && pc > f.Entry() && !wasPanic {
  295. if runtime.GOARCH == "386" || runtime.GOARCH == "amd64" {
  296. tracepc--
  297. } else if runtime.GOARCH == "s390" || runtime.GOARCH == "s390x" {
  298. // only works if function was called
  299. // with the brasl instruction (or a
  300. // different 6-byte instruction).
  301. tracepc -= 6
  302. } else {
  303. tracepc -= 4 // arm, etc
  304. }
  305. }
  306. file, line := f.FileLine(tracepc)
  307. name := f.Name()
  308. // Hide runtime.goexit and any runtime functions at the beginning.
  309. // This is useful mainly for allocation traces.
  310. wasPanic = name == "runtime.panic"
  311. if name == "runtime.goexit" || !show && (strings.HasPrefix(name, "runtime.") || strings.HasPrefix(name, "runtime_")) {
  312. continue
  313. }
  314. if !show && !strings.Contains(name, ".") && strings.HasPrefix(name, "__go_") {
  315. continue
  316. }
  317. if !show && name == "" {
  318. // This can happen due to http://gcc.gnu.org/PR65797.
  319. continue
  320. }
  321. show = true
  322. fmt.Fprintf(w, "#\t%#x\t%s+%#x\t%s:%d\n", pc, name, pc-f.Entry(), file, line)
  323. }
  324. }
  325. if !show {
  326. // We didn't print anything; do it again,
  327. // and this time include runtime functions.
  328. printStackRecord(w, stk, true)
  329. return
  330. }
  331. fmt.Fprintf(w, "\n")
  332. }
  333. // Interface to system profiles.
  334. type byInUseBytes []runtime.MemProfileRecord
  335. func (x byInUseBytes) Len() int { return len(x) }
  336. func (x byInUseBytes) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
  337. func (x byInUseBytes) Less(i, j int) bool { return x[i].InUseBytes() > x[j].InUseBytes() }
  338. // WriteHeapProfile is shorthand for Lookup("heap").WriteTo(w, 0).
  339. // It is preserved for backwards compatibility.
  340. func WriteHeapProfile(w io.Writer) error {
  341. return writeHeap(w, 0)
  342. }
  343. // countHeap returns the number of records in the heap profile.
  344. func countHeap() int {
  345. n, _ := runtime.MemProfile(nil, true)
  346. return n
  347. }
  348. // writeHeap writes the current runtime heap profile to w.
  349. func writeHeap(w io.Writer, debug int) error {
  350. // Find out how many records there are (MemProfile(nil, true)),
  351. // allocate that many records, and get the data.
  352. // There's a race—more records might be added between
  353. // the two calls—so allocate a few extra records for safety
  354. // and also try again if we're very unlucky.
  355. // The loop should only execute one iteration in the common case.
  356. var p []runtime.MemProfileRecord
  357. n, ok := runtime.MemProfile(nil, true)
  358. for {
  359. // Allocate room for a slightly bigger profile,
  360. // in case a few more entries have been added
  361. // since the call to MemProfile.
  362. p = make([]runtime.MemProfileRecord, n+50)
  363. n, ok = runtime.MemProfile(p, true)
  364. if ok {
  365. p = p[0:n]
  366. break
  367. }
  368. // Profile grew; try again.
  369. }
  370. sort.Sort(byInUseBytes(p))
  371. b := bufio.NewWriter(w)
  372. var tw *tabwriter.Writer
  373. w = b
  374. if debug > 0 {
  375. tw = tabwriter.NewWriter(w, 1, 8, 1, '\t', 0)
  376. w = tw
  377. }
  378. var total runtime.MemProfileRecord
  379. for i := range p {
  380. r := &p[i]
  381. total.AllocBytes += r.AllocBytes
  382. total.AllocObjects += r.AllocObjects
  383. total.FreeBytes += r.FreeBytes
  384. total.FreeObjects += r.FreeObjects
  385. }
  386. // Technically the rate is MemProfileRate not 2*MemProfileRate,
  387. // but early versions of the C++ heap profiler reported 2*MemProfileRate,
  388. // so that's what pprof has come to expect.
  389. fmt.Fprintf(w, "heap profile: %d: %d [%d: %d] @ heap/%d\n",
  390. total.InUseObjects(), total.InUseBytes(),
  391. total.AllocObjects, total.AllocBytes,
  392. 2*runtime.MemProfileRate)
  393. for i := range p {
  394. r := &p[i]
  395. fmt.Fprintf(w, "%d: %d [%d: %d] @",
  396. r.InUseObjects(), r.InUseBytes(),
  397. r.AllocObjects, r.AllocBytes)
  398. for _, pc := range r.Stack() {
  399. fmt.Fprintf(w, " %#x", pc)
  400. }
  401. fmt.Fprintf(w, "\n")
  402. if debug > 0 {
  403. printStackRecord(w, r.Stack(), false)
  404. }
  405. }
  406. // Print memstats information too.
  407. // Pprof will ignore, but useful for people
  408. if debug > 0 {
  409. s := new(runtime.MemStats)
  410. runtime.ReadMemStats(s)
  411. fmt.Fprintf(w, "\n# runtime.MemStats\n")
  412. fmt.Fprintf(w, "# Alloc = %d\n", s.Alloc)
  413. fmt.Fprintf(w, "# TotalAlloc = %d\n", s.TotalAlloc)
  414. fmt.Fprintf(w, "# Sys = %d\n", s.Sys)
  415. fmt.Fprintf(w, "# Lookups = %d\n", s.Lookups)
  416. fmt.Fprintf(w, "# Mallocs = %d\n", s.Mallocs)
  417. fmt.Fprintf(w, "# Frees = %d\n", s.Frees)
  418. fmt.Fprintf(w, "# HeapAlloc = %d\n", s.HeapAlloc)
  419. fmt.Fprintf(w, "# HeapSys = %d\n", s.HeapSys)
  420. fmt.Fprintf(w, "# HeapIdle = %d\n", s.HeapIdle)
  421. fmt.Fprintf(w, "# HeapInuse = %d\n", s.HeapInuse)
  422. fmt.Fprintf(w, "# HeapReleased = %d\n", s.HeapReleased)
  423. fmt.Fprintf(w, "# HeapObjects = %d\n", s.HeapObjects)
  424. fmt.Fprintf(w, "# Stack = %d / %d\n", s.StackInuse, s.StackSys)
  425. fmt.Fprintf(w, "# MSpan = %d / %d\n", s.MSpanInuse, s.MSpanSys)
  426. fmt.Fprintf(w, "# MCache = %d / %d\n", s.MCacheInuse, s.MCacheSys)
  427. fmt.Fprintf(w, "# BuckHashSys = %d\n", s.BuckHashSys)
  428. fmt.Fprintf(w, "# NextGC = %d\n", s.NextGC)
  429. fmt.Fprintf(w, "# PauseNs = %d\n", s.PauseNs)
  430. fmt.Fprintf(w, "# NumGC = %d\n", s.NumGC)
  431. fmt.Fprintf(w, "# EnableGC = %v\n", s.EnableGC)
  432. fmt.Fprintf(w, "# DebugGC = %v\n", s.DebugGC)
  433. }
  434. if tw != nil {
  435. tw.Flush()
  436. }
  437. return b.Flush()
  438. }
  439. // countThreadCreate returns the size of the current ThreadCreateProfile.
  440. func countThreadCreate() int {
  441. n, _ := runtime.ThreadCreateProfile(nil)
  442. return n
  443. }
  444. // writeThreadCreate writes the current runtime ThreadCreateProfile to w.
  445. func writeThreadCreate(w io.Writer, debug int) error {
  446. return writeRuntimeProfile(w, debug, "threadcreate", runtime.ThreadCreateProfile)
  447. }
  448. // countGoroutine returns the number of goroutines.
  449. func countGoroutine() int {
  450. return runtime.NumGoroutine()
  451. }
  452. // writeGoroutine writes the current runtime GoroutineProfile to w.
  453. func writeGoroutine(w io.Writer, debug int) error {
  454. if debug >= 2 {
  455. return writeGoroutineStacks(w)
  456. }
  457. return writeRuntimeProfile(w, debug, "goroutine", runtime.GoroutineProfile)
  458. }
  459. func writeGoroutineStacks(w io.Writer) error {
  460. // We don't know how big the buffer needs to be to collect
  461. // all the goroutines. Start with 1 MB and try a few times, doubling each time.
  462. // Give up and use a truncated trace if 64 MB is not enough.
  463. buf := make([]byte, 1<<20)
  464. for i := 0; ; i++ {
  465. n := runtime.Stack(buf, true)
  466. if n < len(buf) {
  467. buf = buf[:n]
  468. break
  469. }
  470. if len(buf) >= 64<<20 {
  471. // Filled 64 MB - stop there.
  472. break
  473. }
  474. buf = make([]byte, 2*len(buf))
  475. }
  476. _, err := w.Write(buf)
  477. return err
  478. }
  479. func writeRuntimeProfile(w io.Writer, debug int, name string, fetch func([]runtime.StackRecord) (int, bool)) error {
  480. // Find out how many records there are (fetch(nil)),
  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.StackRecord
  487. n, ok := fetch(nil)
  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 ThreadProfile.
  492. p = make([]runtime.StackRecord, n+10)
  493. n, ok = fetch(p)
  494. if ok {
  495. p = p[0:n]
  496. break
  497. }
  498. // Profile grew; try again.
  499. }
  500. return printCountProfile(w, debug, name, runtimeProfile(p))
  501. }
  502. type runtimeProfile []runtime.StackRecord
  503. func (p runtimeProfile) Len() int { return len(p) }
  504. func (p runtimeProfile) Stack(i int) []uintptr { return p[i].Stack() }
  505. var cpu struct {
  506. sync.Mutex
  507. profiling bool
  508. done chan bool
  509. }
  510. // StartCPUProfile enables CPU profiling for the current process.
  511. // While profiling, the profile will be buffered and written to w.
  512. // StartCPUProfile returns an error if profiling is already enabled.
  513. func StartCPUProfile(w io.Writer) error {
  514. // The runtime routines allow a variable profiling rate,
  515. // but in practice operating systems cannot trigger signals
  516. // at more than about 500 Hz, and our processing of the
  517. // signal is not cheap (mostly getting the stack trace).
  518. // 100 Hz is a reasonable choice: it is frequent enough to
  519. // produce useful data, rare enough not to bog down the
  520. // system, and a nice round number to make it easy to
  521. // convert sample counts to seconds. Instead of requiring
  522. // each client to specify the frequency, we hard code it.
  523. const hz = 100
  524. cpu.Lock()
  525. defer cpu.Unlock()
  526. if cpu.done == nil {
  527. cpu.done = make(chan bool)
  528. }
  529. // Double-check.
  530. if cpu.profiling {
  531. return fmt.Errorf("cpu profiling already in use")
  532. }
  533. cpu.profiling = true
  534. runtime.SetCPUProfileRate(hz)
  535. go profileWriter(w)
  536. return nil
  537. }
  538. func profileWriter(w io.Writer) {
  539. for {
  540. data := runtime.CPUProfile()
  541. if data == nil {
  542. break
  543. }
  544. w.Write(data)
  545. }
  546. cpu.done <- true
  547. }
  548. // StopCPUProfile stops the current CPU profile, if any.
  549. // StopCPUProfile only returns after all the writes for the
  550. // profile have completed.
  551. func StopCPUProfile() {
  552. cpu.Lock()
  553. defer cpu.Unlock()
  554. if !cpu.profiling {
  555. return
  556. }
  557. cpu.profiling = false
  558. runtime.SetCPUProfileRate(0)
  559. <-cpu.done
  560. }
  561. type byCycles []runtime.BlockProfileRecord
  562. func (x byCycles) Len() int { return len(x) }
  563. func (x byCycles) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
  564. func (x byCycles) Less(i, j int) bool { return x[i].Cycles > x[j].Cycles }
  565. // countBlock returns the number of records in the blocking profile.
  566. func countBlock() int {
  567. n, _ := runtime.BlockProfile(nil)
  568. return n
  569. }
  570. // writeBlock writes the current blocking profile to w.
  571. func writeBlock(w io.Writer, debug int) error {
  572. var p []runtime.BlockProfileRecord
  573. n, ok := runtime.BlockProfile(nil)
  574. for {
  575. p = make([]runtime.BlockProfileRecord, n+50)
  576. n, ok = runtime.BlockProfile(p)
  577. if ok {
  578. p = p[:n]
  579. break
  580. }
  581. }
  582. sort.Sort(byCycles(p))
  583. b := bufio.NewWriter(w)
  584. var tw *tabwriter.Writer
  585. w = b
  586. if debug > 0 {
  587. tw = tabwriter.NewWriter(w, 1, 8, 1, '\t', 0)
  588. w = tw
  589. }
  590. fmt.Fprintf(w, "--- contention:\n")
  591. fmt.Fprintf(w, "cycles/second=%v\n", runtime_cyclesPerSecond())
  592. for i := range p {
  593. r := &p[i]
  594. fmt.Fprintf(w, "%v %v @", r.Cycles, r.Count)
  595. for _, pc := range r.Stack() {
  596. fmt.Fprintf(w, " %#x", pc)
  597. }
  598. fmt.Fprint(w, "\n")
  599. if debug > 0 {
  600. printStackRecord(w, r.Stack(), true)
  601. }
  602. }
  603. if tw != nil {
  604. tw.Flush()
  605. }
  606. return b.Flush()
  607. }
  608. func runtime_cyclesPerSecond() int64