Ingen beskrivning

report.go 31KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141
  1. // Copyright 2014 Google Inc. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // Package report summarizes a performance profile into a
  15. // human-readable report.
  16. package report
  17. import (
  18. "fmt"
  19. "io"
  20. "math"
  21. "path/filepath"
  22. "regexp"
  23. "sort"
  24. "strconv"
  25. "strings"
  26. "time"
  27. "github.com/google/pprof/internal/graph"
  28. "github.com/google/pprof/internal/measurement"
  29. "github.com/google/pprof/internal/plugin"
  30. "github.com/google/pprof/profile"
  31. )
  32. // Output formats.
  33. const (
  34. Callgrind = iota
  35. Comments
  36. Dis
  37. Dot
  38. List
  39. Proto
  40. Raw
  41. Tags
  42. Text
  43. TopProto
  44. Traces
  45. Tree
  46. WebList
  47. )
  48. // Options are the formatting and filtering options used to generate a
  49. // profile.
  50. type Options struct {
  51. OutputFormat int
  52. CumSort bool
  53. CallTree bool
  54. DropNegative bool
  55. PositivePercentages bool
  56. CompactLabels bool
  57. Ratio float64
  58. Title string
  59. ProfileLabels []string
  60. NodeCount int
  61. NodeFraction float64
  62. EdgeFraction float64
  63. SampleValue func(s []int64) int64
  64. SampleMeanDivisor func(s []int64) int64
  65. SampleType string
  66. SampleUnit string // Unit for the sample data from the profile.
  67. OutputUnit string // Units for data formatting in report.
  68. Symbol *regexp.Regexp // Symbols to include on disassembly report.
  69. SourcePath string // Search path for source files.
  70. }
  71. // Generate generates a report as directed by the Report.
  72. func Generate(w io.Writer, rpt *Report, obj plugin.ObjTool) error {
  73. o := rpt.options
  74. switch o.OutputFormat {
  75. case Comments:
  76. return printComments(w, rpt)
  77. case Dot:
  78. return printDOT(w, rpt)
  79. case Tree:
  80. return printTree(w, rpt)
  81. case Text:
  82. return printText(w, rpt)
  83. case Traces:
  84. return printTraces(w, rpt)
  85. case Raw:
  86. fmt.Fprint(w, rpt.prof.String())
  87. return nil
  88. case Tags:
  89. return printTags(w, rpt)
  90. case Proto:
  91. return rpt.prof.Write(w)
  92. case TopProto:
  93. return printTopProto(w, rpt)
  94. case Dis:
  95. return printAssembly(w, rpt, obj)
  96. case List:
  97. return printSource(w, rpt)
  98. case WebList:
  99. return printWebSource(w, rpt, obj)
  100. case Callgrind:
  101. return printCallgrind(w, rpt)
  102. }
  103. return fmt.Errorf("unexpected output format")
  104. }
  105. // newTrimmedGraph creates a graph for this report, trimmed according
  106. // to the report options.
  107. func (rpt *Report) newTrimmedGraph() (g *graph.Graph, origCount, droppedNodes, droppedEdges int) {
  108. o := rpt.options
  109. // Build a graph and refine it. On each refinement step we must rebuild the graph from the samples,
  110. // as the graph itself doesn't contain enough information to preserve full precision.
  111. visualMode := o.OutputFormat == Dot
  112. cumSort := o.CumSort
  113. // First step: Build complete graph to identify low frequency nodes, based on their cum weight.
  114. g = rpt.newGraph(nil)
  115. totalValue, _ := g.Nodes.Sum()
  116. nodeCutoff := abs64(int64(float64(totalValue) * o.NodeFraction))
  117. edgeCutoff := abs64(int64(float64(totalValue) * o.EdgeFraction))
  118. // Filter out nodes with cum value below nodeCutoff.
  119. if nodeCutoff > 0 {
  120. if o.CallTree {
  121. if nodesKept := g.DiscardLowFrequencyNodePtrs(nodeCutoff); len(g.Nodes) != len(nodesKept) {
  122. droppedNodes = len(g.Nodes) - len(nodesKept)
  123. g.TrimTree(nodesKept)
  124. }
  125. } else {
  126. if nodesKept := g.DiscardLowFrequencyNodes(nodeCutoff); len(g.Nodes) != len(nodesKept) {
  127. droppedNodes = len(g.Nodes) - len(nodesKept)
  128. g = rpt.newGraph(nodesKept)
  129. }
  130. }
  131. }
  132. origCount = len(g.Nodes)
  133. // Second step: Limit the total number of nodes. Apply specialized heuristics to improve
  134. // visualization when generating dot output.
  135. g.SortNodes(cumSort, visualMode)
  136. if nodeCount := o.NodeCount; nodeCount > 0 {
  137. // Remove low frequency tags and edges as they affect selection.
  138. g.TrimLowFrequencyTags(nodeCutoff)
  139. g.TrimLowFrequencyEdges(edgeCutoff)
  140. if o.CallTree {
  141. if nodesKept := g.SelectTopNodePtrs(nodeCount, visualMode); len(g.Nodes) != len(nodesKept) {
  142. g.TrimTree(nodesKept)
  143. g.SortNodes(cumSort, visualMode)
  144. }
  145. } else {
  146. if nodesKept := g.SelectTopNodes(nodeCount, visualMode); len(g.Nodes) != len(nodesKept) {
  147. g = rpt.newGraph(nodesKept)
  148. g.SortNodes(cumSort, visualMode)
  149. }
  150. }
  151. }
  152. // Final step: Filter out low frequency tags and edges, and remove redundant edges that clutter
  153. // the graph.
  154. g.TrimLowFrequencyTags(nodeCutoff)
  155. droppedEdges = g.TrimLowFrequencyEdges(edgeCutoff)
  156. if visualMode {
  157. g.RemoveRedundantEdges()
  158. }
  159. return
  160. }
  161. func (rpt *Report) selectOutputUnit(g *graph.Graph) {
  162. o := rpt.options
  163. // Select best unit for profile output.
  164. // Find the appropriate units for the smallest non-zero sample
  165. if o.OutputUnit != "minimum" || len(g.Nodes) == 0 {
  166. return
  167. }
  168. var minValue int64
  169. for _, n := range g.Nodes {
  170. nodeMin := abs64(n.FlatValue())
  171. if nodeMin == 0 {
  172. nodeMin = abs64(n.CumValue())
  173. }
  174. if nodeMin > 0 && (minValue == 0 || nodeMin < minValue) {
  175. minValue = nodeMin
  176. }
  177. }
  178. maxValue := rpt.total
  179. if minValue == 0 {
  180. minValue = maxValue
  181. }
  182. if r := o.Ratio; r > 0 && r != 1 {
  183. minValue = int64(float64(minValue) * r)
  184. maxValue = int64(float64(maxValue) * r)
  185. }
  186. _, minUnit := measurement.Scale(minValue, o.SampleUnit, "minimum")
  187. _, maxUnit := measurement.Scale(maxValue, o.SampleUnit, "minimum")
  188. unit := minUnit
  189. if minUnit != maxUnit && minValue*100 < maxValue && o.OutputFormat != Callgrind {
  190. // Minimum and maximum values have different units. Scale
  191. // minimum by 100 to use larger units, allowing minimum value to
  192. // be scaled down to 0.01, except for callgrind reports since
  193. // they can only represent integer values.
  194. _, unit = measurement.Scale(100*minValue, o.SampleUnit, "minimum")
  195. }
  196. if unit != "" {
  197. o.OutputUnit = unit
  198. } else {
  199. o.OutputUnit = o.SampleUnit
  200. }
  201. }
  202. // newGraph creates a new graph for this report. If nodes is non-nil,
  203. // only nodes whose info matches are included. Otherwise, all nodes
  204. // are included, without trimming.
  205. func (rpt *Report) newGraph(nodes graph.NodeSet) *graph.Graph {
  206. o := rpt.options
  207. // Clean up file paths using heuristics.
  208. prof := rpt.prof
  209. for _, f := range prof.Function {
  210. f.Filename = trimPath(f.Filename)
  211. }
  212. // Remove numeric tags not recognized by pprof.
  213. for _, s := range prof.Sample {
  214. numLabels := make(map[string][]int64, len(s.NumLabel))
  215. for k, v := range s.NumLabel {
  216. if k == "bytes" {
  217. numLabels[k] = append(numLabels[k], v...)
  218. }
  219. }
  220. s.NumLabel = numLabels
  221. }
  222. formatTag := func(v int64, key string) string {
  223. return measurement.ScaledLabel(v, key, o.OutputUnit)
  224. }
  225. gopt := &graph.Options{
  226. SampleValue: o.SampleValue,
  227. SampleMeanDivisor: o.SampleMeanDivisor,
  228. FormatTag: formatTag,
  229. CallTree: o.CallTree && (o.OutputFormat == Dot || o.OutputFormat == Callgrind),
  230. DropNegative: o.DropNegative,
  231. KeptNodes: nodes,
  232. }
  233. // Only keep binary names for disassembly-based reports, otherwise
  234. // remove it to allow merging of functions across binaries.
  235. switch o.OutputFormat {
  236. case Raw, List, WebList, Dis, Callgrind:
  237. gopt.ObjNames = true
  238. }
  239. return graph.New(rpt.prof, gopt)
  240. }
  241. func printTopProto(w io.Writer, rpt *Report) error {
  242. p := rpt.prof
  243. o := rpt.options
  244. g, _, _, _ := rpt.newTrimmedGraph()
  245. rpt.selectOutputUnit(g)
  246. out := profile.Profile{
  247. SampleType: []*profile.ValueType{
  248. {Type: "cum", Unit: o.OutputUnit},
  249. {Type: "flat", Unit: o.OutputUnit},
  250. },
  251. TimeNanos: p.TimeNanos,
  252. DurationNanos: p.DurationNanos,
  253. PeriodType: p.PeriodType,
  254. Period: p.Period,
  255. }
  256. var flatSum int64
  257. for i, n := range g.Nodes {
  258. name, flat, cum := n.Info.PrintableName(), n.FlatValue(), n.CumValue()
  259. flatSum += flat
  260. f := &profile.Function{
  261. ID: uint64(i + 1),
  262. Name: name,
  263. SystemName: name,
  264. }
  265. l := &profile.Location{
  266. ID: uint64(i + 1),
  267. Line: []profile.Line{
  268. {
  269. Function: f,
  270. },
  271. },
  272. }
  273. fv, _ := measurement.Scale(flat, o.SampleUnit, o.OutputUnit)
  274. cv, _ := measurement.Scale(cum, o.SampleUnit, o.OutputUnit)
  275. s := &profile.Sample{
  276. Location: []*profile.Location{l},
  277. Value: []int64{int64(cv), int64(fv)},
  278. }
  279. out.Function = append(out.Function, f)
  280. out.Location = append(out.Location, l)
  281. out.Sample = append(out.Sample, s)
  282. }
  283. return out.Write(w)
  284. }
  285. // printAssembly prints an annotated assembly listing.
  286. func printAssembly(w io.Writer, rpt *Report, obj plugin.ObjTool) error {
  287. o := rpt.options
  288. prof := rpt.prof
  289. g := rpt.newGraph(nil)
  290. // If the regexp source can be parsed as an address, also match
  291. // functions that land on that address.
  292. var address *uint64
  293. if hex, err := strconv.ParseUint(o.Symbol.String(), 0, 64); err == nil {
  294. address = &hex
  295. }
  296. fmt.Fprintln(w, "Total:", rpt.formatValue(rpt.total))
  297. symbols := symbolsFromBinaries(prof, g, o.Symbol, address, obj)
  298. symNodes := nodesPerSymbol(g.Nodes, symbols)
  299. // Sort function names for printing.
  300. var syms objSymbols
  301. for s := range symNodes {
  302. syms = append(syms, s)
  303. }
  304. sort.Sort(syms)
  305. // Correlate the symbols from the binary with the profile samples.
  306. for _, s := range syms {
  307. sns := symNodes[s]
  308. // Gather samples for this symbol.
  309. flatSum, cumSum := sns.Sum()
  310. // Get the function assembly.
  311. insts, err := obj.Disasm(s.sym.File, s.sym.Start, s.sym.End)
  312. if err != nil {
  313. return err
  314. }
  315. ns := annotateAssembly(insts, sns, s.base)
  316. fmt.Fprintf(w, "ROUTINE ======================== %s\n", s.sym.Name[0])
  317. for _, name := range s.sym.Name[1:] {
  318. fmt.Fprintf(w, " AKA ======================== %s\n", name)
  319. }
  320. fmt.Fprintf(w, "%10s %10s (flat, cum) %s of Total\n",
  321. rpt.formatValue(flatSum), rpt.formatValue(cumSum),
  322. percentage(cumSum, rpt.total))
  323. function, file, line := "", "", 0
  324. for _, n := range ns {
  325. flat := valueOrDot(n.flatValue(), rpt)
  326. cum := valueOrDot(n.cumValue(), rpt)
  327. if n.function == function && n.file == file && n.line == line {
  328. fmt.Fprintf(w, "%10s %10s %10x: %s\n",
  329. flat, cum,
  330. n.address, n.instruction,
  331. )
  332. continue
  333. }
  334. line := ""
  335. if n.line > 0 {
  336. line = fmt.Sprintf(":%d", n.line)
  337. }
  338. if len(n.instruction) <= 40 {
  339. fmt.Fprintf(w, "%10s %10s %10x: %-40s; %s %s%s\n",
  340. flat, cum,
  341. n.address, n.instruction,
  342. n.function, n.file, line,
  343. )
  344. continue
  345. }
  346. fmt.Fprintf(w, "%75s; %s %s%s\n",
  347. "",
  348. n.function, n.file, line,
  349. )
  350. fmt.Fprintf(w, "%10s %10s %10x: %s\n",
  351. flat, cum,
  352. n.address, n.instruction,
  353. )
  354. }
  355. }
  356. return nil
  357. }
  358. // symbolsFromBinaries examines the binaries listed on the profile
  359. // that have associated samples, and identifies symbols matching rx.
  360. func symbolsFromBinaries(prof *profile.Profile, g *graph.Graph, rx *regexp.Regexp, address *uint64, obj plugin.ObjTool) []*objSymbol {
  361. hasSamples := make(map[string]bool)
  362. // Only examine mappings that have samples that match the
  363. // regexp. This is an optimization to speed up pprof.
  364. for _, n := range g.Nodes {
  365. if name := n.Info.PrintableName(); rx.MatchString(name) && n.Info.Objfile != "" {
  366. hasSamples[n.Info.Objfile] = true
  367. }
  368. }
  369. // Walk all mappings looking for matching functions with samples.
  370. var objSyms []*objSymbol
  371. for _, m := range prof.Mapping {
  372. if !hasSamples[m.File] {
  373. if address == nil || !(m.Start <= *address && *address <= m.Limit) {
  374. continue
  375. }
  376. }
  377. f, err := obj.Open(m.File, m.Start, m.Limit, m.Offset)
  378. if err != nil {
  379. fmt.Printf("%v\n", err)
  380. continue
  381. }
  382. // Find symbols in this binary matching the user regexp.
  383. var addr uint64
  384. if address != nil {
  385. addr = *address
  386. }
  387. msyms, err := f.Symbols(rx, addr)
  388. base := f.Base()
  389. f.Close()
  390. if err != nil {
  391. continue
  392. }
  393. for _, ms := range msyms {
  394. objSyms = append(objSyms,
  395. &objSymbol{
  396. sym: ms,
  397. base: base,
  398. },
  399. )
  400. }
  401. }
  402. return objSyms
  403. }
  404. // objSym represents a symbol identified from a binary. It includes
  405. // the SymbolInfo from the disasm package and the base that must be
  406. // added to correspond to sample addresses
  407. type objSymbol struct {
  408. sym *plugin.Sym
  409. base uint64
  410. }
  411. // objSymbols is a wrapper type to enable sorting of []*objSymbol.
  412. type objSymbols []*objSymbol
  413. func (o objSymbols) Len() int {
  414. return len(o)
  415. }
  416. func (o objSymbols) Less(i, j int) bool {
  417. if namei, namej := o[i].sym.Name[0], o[j].sym.Name[0]; namei != namej {
  418. return namei < namej
  419. }
  420. return o[i].sym.Start < o[j].sym.Start
  421. }
  422. func (o objSymbols) Swap(i, j int) {
  423. o[i], o[j] = o[j], o[i]
  424. }
  425. // nodesPerSymbol classifies nodes into a group of symbols.
  426. func nodesPerSymbol(ns graph.Nodes, symbols []*objSymbol) map[*objSymbol]graph.Nodes {
  427. symNodes := make(map[*objSymbol]graph.Nodes)
  428. for _, s := range symbols {
  429. // Gather samples for this symbol.
  430. for _, n := range ns {
  431. address := n.Info.Address - s.base
  432. if address >= s.sym.Start && address < s.sym.End {
  433. symNodes[s] = append(symNodes[s], n)
  434. }
  435. }
  436. }
  437. return symNodes
  438. }
  439. type assemblyInstruction struct {
  440. address uint64
  441. instruction string
  442. function string
  443. file string
  444. line int
  445. flat, cum int64
  446. flatDiv, cumDiv int64
  447. }
  448. func (a *assemblyInstruction) flatValue() int64 {
  449. if a.flatDiv != 0 {
  450. return a.flat / a.flatDiv
  451. }
  452. return a.flat
  453. }
  454. func (a *assemblyInstruction) cumValue() int64 {
  455. if a.cumDiv != 0 {
  456. return a.cum / a.cumDiv
  457. }
  458. return a.cum
  459. }
  460. // annotateAssembly annotates a set of assembly instructions with a
  461. // set of samples. It returns a set of nodes to display. base is an
  462. // offset to adjust the sample addresses.
  463. func annotateAssembly(insts []plugin.Inst, samples graph.Nodes, base uint64) []assemblyInstruction {
  464. // Add end marker to simplify printing loop.
  465. insts = append(insts, plugin.Inst{
  466. Addr: ^uint64(0),
  467. })
  468. // Ensure samples are sorted by address.
  469. samples.Sort(graph.AddressOrder)
  470. s := 0
  471. asm := make([]assemblyInstruction, 0, len(insts))
  472. for ix, in := range insts[:len(insts)-1] {
  473. n := assemblyInstruction{
  474. address: in.Addr,
  475. instruction: in.Text,
  476. function: in.Function,
  477. line: in.Line,
  478. }
  479. if in.File != "" {
  480. n.file = filepath.Base(in.File)
  481. }
  482. // Sum all the samples until the next instruction (to account
  483. // for samples attributed to the middle of an instruction).
  484. for next := insts[ix+1].Addr; s < len(samples) && samples[s].Info.Address-base < next; s++ {
  485. sample := samples[s]
  486. n.flatDiv += sample.FlatDiv
  487. n.flat += sample.Flat
  488. n.cumDiv += sample.CumDiv
  489. n.cum += sample.Cum
  490. if f := sample.Info.File; f != "" && n.file == "" {
  491. n.file = filepath.Base(f)
  492. }
  493. if ln := sample.Info.Lineno; ln != 0 && n.line == 0 {
  494. n.line = ln
  495. }
  496. if f := sample.Info.Name; f != "" && n.function == "" {
  497. n.function = f
  498. }
  499. }
  500. asm = append(asm, n)
  501. }
  502. return asm
  503. }
  504. // valueOrDot formats a value according to a report, intercepting zero
  505. // values.
  506. func valueOrDot(value int64, rpt *Report) string {
  507. if value == 0 {
  508. return "."
  509. }
  510. return rpt.formatValue(value)
  511. }
  512. // printTags collects all tags referenced in the profile and prints
  513. // them in a sorted table.
  514. func printTags(w io.Writer, rpt *Report) error {
  515. p := rpt.prof
  516. o := rpt.options
  517. formatTag := func(v int64, key string) string {
  518. return measurement.ScaledLabel(v, key, o.OutputUnit)
  519. }
  520. // Hashtable to keep accumulate tags as key,value,count.
  521. tagMap := make(map[string]map[string]int64)
  522. for _, s := range p.Sample {
  523. for key, vals := range s.Label {
  524. for _, val := range vals {
  525. if valueMap, ok := tagMap[key]; ok {
  526. valueMap[val] = valueMap[val] + s.Value[0]
  527. continue
  528. }
  529. valueMap := make(map[string]int64)
  530. valueMap[val] = s.Value[0]
  531. tagMap[key] = valueMap
  532. }
  533. }
  534. for key, vals := range s.NumLabel {
  535. for _, nval := range vals {
  536. val := formatTag(nval, key)
  537. if valueMap, ok := tagMap[key]; ok {
  538. valueMap[val] = valueMap[val] + s.Value[0]
  539. continue
  540. }
  541. valueMap := make(map[string]int64)
  542. valueMap[val] = s.Value[0]
  543. tagMap[key] = valueMap
  544. }
  545. }
  546. }
  547. tagKeys := make([]*graph.Tag, 0, len(tagMap))
  548. for key := range tagMap {
  549. tagKeys = append(tagKeys, &graph.Tag{Name: key})
  550. }
  551. for _, tagKey := range graph.SortTags(tagKeys, true) {
  552. var total int64
  553. key := tagKey.Name
  554. tags := make([]*graph.Tag, 0, len(tagMap[key]))
  555. for t, c := range tagMap[key] {
  556. total += c
  557. tags = append(tags, &graph.Tag{Name: t, Flat: c})
  558. }
  559. fmt.Fprintf(w, "%s: Total %d\n", key, total)
  560. for _, t := range graph.SortTags(tags, true) {
  561. if total > 0 {
  562. fmt.Fprintf(w, " %8d (%s): %s\n", t.FlatValue(),
  563. percentage(t.FlatValue(), total), t.Name)
  564. } else {
  565. fmt.Fprintf(w, " %8d: %s\n", t.FlatValue(), t.Name)
  566. }
  567. }
  568. fmt.Fprintln(w)
  569. }
  570. return nil
  571. }
  572. // printComments prints all freeform comments in the profile.
  573. func printComments(w io.Writer, rpt *Report) error {
  574. p := rpt.prof
  575. for _, c := range p.Comments {
  576. fmt.Fprintln(w, c)
  577. }
  578. return nil
  579. }
  580. // printText prints a flat text report for a profile.
  581. func printText(w io.Writer, rpt *Report) error {
  582. g, origCount, droppedNodes, _ := rpt.newTrimmedGraph()
  583. rpt.selectOutputUnit(g)
  584. fmt.Fprintln(w, strings.Join(reportLabels(rpt, g, origCount, droppedNodes, 0, false), "\n"))
  585. fmt.Fprintf(w, "%10s %5s%% %5s%% %10s %5s%%\n",
  586. "flat", "flat", "sum", "cum", "cum")
  587. var flatSum int64
  588. for _, n := range g.Nodes {
  589. name, flat, cum := n.Info.PrintableName(), n.FlatValue(), n.CumValue()
  590. var inline, noinline bool
  591. for _, e := range n.In {
  592. if e.Inline {
  593. inline = true
  594. } else {
  595. noinline = true
  596. }
  597. }
  598. if inline {
  599. if noinline {
  600. name = name + " (partial-inline)"
  601. } else {
  602. name = name + " (inline)"
  603. }
  604. }
  605. flatSum += flat
  606. fmt.Fprintf(w, "%10s %s %s %10s %s %s\n",
  607. rpt.formatValue(flat),
  608. percentage(flat, rpt.total),
  609. percentage(flatSum, rpt.total),
  610. rpt.formatValue(cum),
  611. percentage(cum, rpt.total),
  612. name)
  613. }
  614. return nil
  615. }
  616. // printTraces prints all traces from a profile.
  617. func printTraces(w io.Writer, rpt *Report) error {
  618. fmt.Fprintln(w, strings.Join(ProfileLabels(rpt), "\n"))
  619. prof := rpt.prof
  620. o := rpt.options
  621. const separator = "-----------+-------------------------------------------------------"
  622. _, locations := graph.CreateNodes(prof, &graph.Options{})
  623. for _, sample := range prof.Sample {
  624. var stack graph.Nodes
  625. for _, loc := range sample.Location {
  626. id := loc.ID
  627. stack = append(stack, locations[id]...)
  628. }
  629. if len(stack) == 0 {
  630. continue
  631. }
  632. fmt.Fprintln(w, separator)
  633. // Print any text labels for the sample.
  634. var labels []string
  635. for s, vs := range sample.Label {
  636. labels = append(labels, fmt.Sprintf("%10s: %s\n", s, strings.Join(vs, " ")))
  637. }
  638. sort.Strings(labels)
  639. fmt.Fprint(w, strings.Join(labels, ""))
  640. var d, v int64
  641. v = o.SampleValue(sample.Value)
  642. if o.SampleMeanDivisor != nil {
  643. d = o.SampleMeanDivisor(sample.Value)
  644. }
  645. // Print call stack.
  646. if d != 0 {
  647. v = v / d
  648. }
  649. fmt.Fprintf(w, "%10s %s\n",
  650. rpt.formatValue(v), stack[0].Info.PrintableName())
  651. for _, s := range stack[1:] {
  652. fmt.Fprintf(w, "%10s %s\n", "", s.Info.PrintableName())
  653. }
  654. }
  655. fmt.Fprintln(w, separator)
  656. return nil
  657. }
  658. // printCallgrind prints a graph for a profile on callgrind format.
  659. func printCallgrind(w io.Writer, rpt *Report) error {
  660. o := rpt.options
  661. rpt.options.NodeFraction = 0
  662. rpt.options.EdgeFraction = 0
  663. rpt.options.NodeCount = 0
  664. g, _, _, _ := rpt.newTrimmedGraph()
  665. rpt.selectOutputUnit(g)
  666. nodeNames := getDisambiguatedNames(g)
  667. fmt.Fprintln(w, "positions: instr line")
  668. fmt.Fprintln(w, "events:", o.SampleType+"("+o.OutputUnit+")")
  669. objfiles := make(map[string]int)
  670. files := make(map[string]int)
  671. names := make(map[string]int)
  672. // prevInfo points to the previous NodeInfo.
  673. // It is used to group cost lines together as much as possible.
  674. var prevInfo *graph.NodeInfo
  675. for _, n := range g.Nodes {
  676. if prevInfo == nil || n.Info.Objfile != prevInfo.Objfile || n.Info.File != prevInfo.File || n.Info.Name != prevInfo.Name {
  677. fmt.Fprintln(w)
  678. fmt.Fprintln(w, "ob="+callgrindName(objfiles, n.Info.Objfile))
  679. fmt.Fprintln(w, "fl="+callgrindName(files, n.Info.File))
  680. fmt.Fprintln(w, "fn="+callgrindName(names, n.Info.Name))
  681. }
  682. addr := callgrindAddress(prevInfo, n.Info.Address)
  683. sv, _ := measurement.Scale(n.FlatValue(), o.SampleUnit, o.OutputUnit)
  684. fmt.Fprintf(w, "%s %d %d\n", addr, n.Info.Lineno, int64(sv))
  685. // Print outgoing edges.
  686. for _, out := range n.Out.Sort() {
  687. c, _ := measurement.Scale(out.Weight, o.SampleUnit, o.OutputUnit)
  688. callee := out.Dest
  689. fmt.Fprintln(w, "cfl="+callgrindName(files, callee.Info.File))
  690. fmt.Fprintln(w, "cfn="+callgrindName(names, nodeNames[callee]))
  691. // pprof doesn't have a flat weight for a call, leave as 0.
  692. fmt.Fprintf(w, "calls=0 %s %d\n", callgrindAddress(prevInfo, callee.Info.Address), callee.Info.Lineno)
  693. // TODO: This address may be in the middle of a call
  694. // instruction. It would be best to find the beginning
  695. // of the instruction, but the tools seem to handle
  696. // this OK.
  697. fmt.Fprintf(w, "* * %d\n", int64(c))
  698. }
  699. prevInfo = &n.Info
  700. }
  701. return nil
  702. }
  703. // getDisambiguatedNames returns a map from each node in the graph to
  704. // the name to use in the callgrind output. Callgrind merges all
  705. // functions with the same [file name, function name]. Add a [%d/n]
  706. // suffix to disambiguate nodes with different values of
  707. // node.Function, which we want to keep separate. In particular, this
  708. // affects graphs created with --call_tree, where nodes from different
  709. // contexts are associated to different Functions.
  710. func getDisambiguatedNames(g *graph.Graph) map[*graph.Node]string {
  711. nodeName := make(map[*graph.Node]string, len(g.Nodes))
  712. type names struct {
  713. file, function string
  714. }
  715. // nameFunctionIndex maps the callgrind names (filename, function)
  716. // to the node.Function values found for that name, and each
  717. // node.Function value to a sequential index to be used on the
  718. // disambiguated name.
  719. nameFunctionIndex := make(map[names]map[*graph.Node]int)
  720. for _, n := range g.Nodes {
  721. nm := names{n.Info.File, n.Info.Name}
  722. p, ok := nameFunctionIndex[nm]
  723. if !ok {
  724. p = make(map[*graph.Node]int)
  725. nameFunctionIndex[nm] = p
  726. }
  727. if _, ok := p[n.Function]; !ok {
  728. p[n.Function] = len(p)
  729. }
  730. }
  731. for _, n := range g.Nodes {
  732. nm := names{n.Info.File, n.Info.Name}
  733. nodeName[n] = n.Info.Name
  734. if p := nameFunctionIndex[nm]; len(p) > 1 {
  735. // If there is more than one function, add suffix to disambiguate.
  736. nodeName[n] += fmt.Sprintf(" [%d/%d]", p[n.Function]+1, len(p))
  737. }
  738. }
  739. return nodeName
  740. }
  741. // callgrindName implements the callgrind naming compression scheme.
  742. // For names not previously seen returns "(N) name", where N is a
  743. // unique index. For names previously seen returns "(N)" where N is
  744. // the index returned the first time.
  745. func callgrindName(names map[string]int, name string) string {
  746. if name == "" {
  747. return ""
  748. }
  749. if id, ok := names[name]; ok {
  750. return fmt.Sprintf("(%d)", id)
  751. }
  752. id := len(names) + 1
  753. names[name] = id
  754. return fmt.Sprintf("(%d) %s", id, name)
  755. }
  756. // callgrindAddress implements the callgrind subposition compression scheme if
  757. // possible. If prevInfo != nil, it contains the previous address. The current
  758. // address can be given relative to the previous address, with an explicit +/-
  759. // to indicate it is relative, or * for the same address.
  760. func callgrindAddress(prevInfo *graph.NodeInfo, curr uint64) string {
  761. abs := fmt.Sprintf("%#x", curr)
  762. if prevInfo == nil {
  763. return abs
  764. }
  765. prev := prevInfo.Address
  766. if prev == curr {
  767. return "*"
  768. }
  769. diff := int64(curr - prev)
  770. relative := fmt.Sprintf("%+d", diff)
  771. // Only bother to use the relative address if it is actually shorter.
  772. if len(relative) < len(abs) {
  773. return relative
  774. }
  775. return abs
  776. }
  777. // printTree prints a tree-based report in text form.
  778. func printTree(w io.Writer, rpt *Report) error {
  779. const separator = "----------------------------------------------------------+-------------"
  780. const legend = " flat flat% sum% cum cum% calls calls% + context "
  781. g, origCount, droppedNodes, _ := rpt.newTrimmedGraph()
  782. rpt.selectOutputUnit(g)
  783. fmt.Fprintln(w, strings.Join(reportLabels(rpt, g, origCount, droppedNodes, 0, false), "\n"))
  784. fmt.Fprintln(w, separator)
  785. fmt.Fprintln(w, legend)
  786. var flatSum int64
  787. rx := rpt.options.Symbol
  788. for _, n := range g.Nodes {
  789. name, flat, cum := n.Info.PrintableName(), n.FlatValue(), n.CumValue()
  790. // Skip any entries that do not match the regexp (for the "peek" command).
  791. if rx != nil && !rx.MatchString(name) {
  792. continue
  793. }
  794. fmt.Fprintln(w, separator)
  795. // Print incoming edges.
  796. inEdges := n.In.Sort()
  797. for _, in := range inEdges {
  798. var inline string
  799. if in.Inline {
  800. inline = " (inline)"
  801. }
  802. fmt.Fprintf(w, "%50s %s | %s%s\n", rpt.formatValue(in.Weight),
  803. percentage(in.Weight, cum), in.Src.Info.PrintableName(), inline)
  804. }
  805. // Print current node.
  806. flatSum += flat
  807. fmt.Fprintf(w, "%10s %s %s %10s %s | %s\n",
  808. rpt.formatValue(flat),
  809. percentage(flat, rpt.total),
  810. percentage(flatSum, rpt.total),
  811. rpt.formatValue(cum),
  812. percentage(cum, rpt.total),
  813. name)
  814. // Print outgoing edges.
  815. outEdges := n.Out.Sort()
  816. for _, out := range outEdges {
  817. var inline string
  818. if out.Inline {
  819. inline = " (inline)"
  820. }
  821. fmt.Fprintf(w, "%50s %s | %s%s\n", rpt.formatValue(out.Weight),
  822. percentage(out.Weight, cum), out.Dest.Info.PrintableName(), inline)
  823. }
  824. }
  825. if len(g.Nodes) > 0 {
  826. fmt.Fprintln(w, separator)
  827. }
  828. return nil
  829. }
  830. // printDOT prints an annotated callgraph in DOT format.
  831. func printDOT(w io.Writer, rpt *Report) error {
  832. g, origCount, droppedNodes, droppedEdges := rpt.newTrimmedGraph()
  833. rpt.selectOutputUnit(g)
  834. labels := reportLabels(rpt, g, origCount, droppedNodes, droppedEdges, true)
  835. o := rpt.options
  836. formatTag := func(v int64, key string) string {
  837. return measurement.ScaledLabel(v, key, o.OutputUnit)
  838. }
  839. c := &graph.DotConfig{
  840. Title: rpt.options.Title,
  841. Labels: labels,
  842. FormatValue: rpt.formatValue,
  843. FormatTag: formatTag,
  844. Total: rpt.total,
  845. }
  846. graph.ComposeDot(w, g, &graph.DotAttributes{}, c)
  847. return nil
  848. }
  849. // percentage computes the percentage of total of a value, and encodes
  850. // it as a string. At least two digits of precision are printed.
  851. func percentage(value, total int64) string {
  852. var ratio float64
  853. if total != 0 {
  854. ratio = math.Abs(float64(value)/float64(total)) * 100
  855. }
  856. switch {
  857. case math.Abs(ratio) >= 99.95 && math.Abs(ratio) <= 100.05:
  858. return " 100%"
  859. case math.Abs(ratio) >= 1.0:
  860. return fmt.Sprintf("%5.2f%%", ratio)
  861. default:
  862. return fmt.Sprintf("%5.2g%%", ratio)
  863. }
  864. }
  865. // ProfileLabels returns printable labels for a profile.
  866. func ProfileLabels(rpt *Report) []string {
  867. label := []string{}
  868. prof := rpt.prof
  869. o := rpt.options
  870. if len(prof.Mapping) > 0 {
  871. if prof.Mapping[0].File != "" {
  872. label = append(label, "File: "+filepath.Base(prof.Mapping[0].File))
  873. }
  874. if prof.Mapping[0].BuildID != "" {
  875. label = append(label, "Build ID: "+prof.Mapping[0].BuildID)
  876. }
  877. }
  878. // Only include comments that do not start with '#'.
  879. for _, c := range prof.Comments {
  880. if !strings.HasPrefix(c, "#") {
  881. label = append(label, c)
  882. }
  883. }
  884. if o.SampleType != "" {
  885. label = append(label, "Type: "+o.SampleType)
  886. }
  887. if prof.TimeNanos != 0 {
  888. const layout = "Jan 2, 2006 at 3:04pm (MST)"
  889. label = append(label, "Time: "+time.Unix(0, prof.TimeNanos).Format(layout))
  890. }
  891. if prof.DurationNanos != 0 {
  892. duration := measurement.Label(prof.DurationNanos, "nanoseconds")
  893. totalNanos, totalUnit := measurement.Scale(rpt.total, o.SampleUnit, "nanoseconds")
  894. var ratio string
  895. if totalUnit == "ns" && totalNanos != 0 {
  896. ratio = "(" + percentage(int64(totalNanos), prof.DurationNanos) + ")"
  897. }
  898. label = append(label, fmt.Sprintf("Duration: %s, Total samples = %s %s", duration, rpt.formatValue(rpt.total), ratio))
  899. }
  900. return label
  901. }
  902. // reportLabels returns printable labels for a report. Includes
  903. // profileLabels.
  904. func reportLabels(rpt *Report, g *graph.Graph, origCount, droppedNodes, droppedEdges int, fullHeaders bool) []string {
  905. nodeFraction := rpt.options.NodeFraction
  906. edgeFraction := rpt.options.EdgeFraction
  907. nodeCount := len(g.Nodes)
  908. var label []string
  909. if len(rpt.options.ProfileLabels) > 0 {
  910. for _, l := range rpt.options.ProfileLabels {
  911. label = append(label, l)
  912. }
  913. } else if fullHeaders || !rpt.options.CompactLabels {
  914. label = ProfileLabels(rpt)
  915. }
  916. var flatSum int64
  917. for _, n := range g.Nodes {
  918. flatSum = flatSum + n.FlatValue()
  919. }
  920. label = append(label, fmt.Sprintf("Showing nodes accounting for %s, %s of %s total", rpt.formatValue(flatSum), strings.TrimSpace(percentage(flatSum, rpt.total)), rpt.formatValue(rpt.total)))
  921. if rpt.total != 0 {
  922. if droppedNodes > 0 {
  923. label = append(label, genLabel(droppedNodes, "node", "cum",
  924. rpt.formatValue(abs64(int64(float64(rpt.total)*nodeFraction)))))
  925. }
  926. if droppedEdges > 0 {
  927. label = append(label, genLabel(droppedEdges, "edge", "freq",
  928. rpt.formatValue(abs64(int64(float64(rpt.total)*edgeFraction)))))
  929. }
  930. if nodeCount > 0 && nodeCount < origCount {
  931. label = append(label, fmt.Sprintf("Showing top %d nodes out of %d",
  932. nodeCount, origCount))
  933. }
  934. }
  935. return label
  936. }
  937. func genLabel(d int, n, l, f string) string {
  938. if d > 1 {
  939. n = n + "s"
  940. }
  941. return fmt.Sprintf("Dropped %d %s (%s <= %s)", d, n, l, f)
  942. }
  943. // New builds a new report indexing the sample values interpreting the
  944. // samples with the provided function.
  945. func New(prof *profile.Profile, o *Options) *Report {
  946. format := func(v int64) string {
  947. if r := o.Ratio; r > 0 && r != 1 {
  948. fv := float64(v) * r
  949. v = int64(fv)
  950. }
  951. return measurement.ScaledLabel(v, o.SampleUnit, o.OutputUnit)
  952. }
  953. return &Report{prof, computeTotal(prof, o.SampleValue, o.SampleMeanDivisor, !o.PositivePercentages),
  954. o, format}
  955. }
  956. // NewDefault builds a new report indexing the last sample value
  957. // available.
  958. func NewDefault(prof *profile.Profile, options Options) *Report {
  959. index := len(prof.SampleType) - 1
  960. o := &options
  961. if o.Title == "" && len(prof.Mapping) > 0 && prof.Mapping[0].File != "" {
  962. o.Title = filepath.Base(prof.Mapping[0].File)
  963. }
  964. o.SampleType = prof.SampleType[index].Type
  965. o.SampleUnit = strings.ToLower(prof.SampleType[index].Unit)
  966. o.SampleValue = func(v []int64) int64 {
  967. return v[index]
  968. }
  969. return New(prof, o)
  970. }
  971. // computeTotal computes the sum of all sample values. This will be
  972. // used to compute percentages. If includeNegative is set, use use
  973. // absolute values to provide a meaningful percentage for both
  974. // negative and positive values. Otherwise only use positive values,
  975. // which is useful when comparing profiles from different jobs.
  976. func computeTotal(prof *profile.Profile, value, meanDiv func(v []int64) int64, includeNegative bool) int64 {
  977. var div, ret int64
  978. for _, sample := range prof.Sample {
  979. var d, v int64
  980. v = value(sample.Value)
  981. if meanDiv != nil {
  982. d = meanDiv(sample.Value)
  983. }
  984. if v >= 0 {
  985. ret += v
  986. div += d
  987. } else if includeNegative {
  988. ret -= v
  989. div += d
  990. }
  991. }
  992. if div != 0 {
  993. return ret / div
  994. }
  995. return ret
  996. }
  997. // Report contains the data and associated routines to extract a
  998. // report from a profile.
  999. type Report struct {
  1000. prof *profile.Profile
  1001. total int64
  1002. options *Options
  1003. formatValue func(int64) string
  1004. }
  1005. func abs64(i int64) int64 {
  1006. if i < 0 {
  1007. return -i
  1008. }
  1009. return i
  1010. }