Aucune description

report.go 36KB

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