暫無描述

report.go 35KB

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