暫無描述

report.go 35KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269
  1. // Copyright 2014 Google Inc. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // Package report summarizes a performance profile into a
  15. // human-readable report.
  16. package report
  17. import (
  18. "fmt"
  19. "io"
  20. "math"
  21. "path/filepath"
  22. "regexp"
  23. "sort"
  24. "strconv"
  25. "strings"
  26. "text/tabwriter"
  27. "time"
  28. "github.com/google/pprof/internal/graph"
  29. "github.com/google/pprof/internal/measurement"
  30. "github.com/google/pprof/internal/plugin"
  31. "github.com/google/pprof/profile"
  32. )
  33. // Output formats.
  34. const (
  35. Callgrind = iota
  36. Comments
  37. Dis
  38. Dot
  39. List
  40. Proto
  41. Raw
  42. Tags
  43. Text
  44. TopProto
  45. Traces
  46. Tree
  47. WebList
  48. )
  49. // Options are the formatting and filtering options used to generate a
  50. // profile.
  51. type Options struct {
  52. OutputFormat int
  53. CumSort bool
  54. CallTree bool
  55. DropNegative bool
  56. PositivePercentages bool
  57. CompactLabels bool
  58. Ratio float64
  59. Title string
  60. ProfileLabels []string
  61. ActiveFilters []string
  62. NumLabelUnits map[string]string
  63. NodeCount int
  64. NodeFraction float64
  65. EdgeFraction float64
  66. SampleValue func(s []int64) int64
  67. SampleMeanDivisor func(s []int64) int64
  68. SampleType string
  69. SampleUnit string // Unit for the sample data from the profile.
  70. OutputUnit string // Units for data formatting in report.
  71. Symbol *regexp.Regexp // Symbols to include on disassembly report.
  72. SourcePath string // Search path for source files.
  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 rpt.prof.Write(w)
  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)
  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. formatTag := func(v int64, key string) string {
  240. return measurement.ScaledLabel(v, key, o.OutputUnit)
  241. }
  242. gopt := &graph.Options{
  243. SampleValue: o.SampleValue,
  244. SampleMeanDivisor: o.SampleMeanDivisor,
  245. FormatTag: formatTag,
  246. CallTree: o.CallTree && (o.OutputFormat == Dot || o.OutputFormat == Callgrind),
  247. DropNegative: o.DropNegative,
  248. KeptNodes: nodes,
  249. }
  250. // Only keep binary names for disassembly-based reports, otherwise
  251. // remove it to allow merging of functions across binaries.
  252. switch o.OutputFormat {
  253. case Raw, List, WebList, Dis, Callgrind:
  254. gopt.ObjNames = true
  255. }
  256. return graph.New(rpt.prof, gopt)
  257. }
  258. func printTopProto(w io.Writer, rpt *Report) error {
  259. p := rpt.prof
  260. o := rpt.options
  261. g, _, _, _ := rpt.newTrimmedGraph()
  262. rpt.selectOutputUnit(g)
  263. out := profile.Profile{
  264. SampleType: []*profile.ValueType{
  265. {Type: "cum", Unit: o.OutputUnit},
  266. {Type: "flat", Unit: o.OutputUnit},
  267. },
  268. TimeNanos: p.TimeNanos,
  269. DurationNanos: p.DurationNanos,
  270. PeriodType: p.PeriodType,
  271. Period: p.Period,
  272. }
  273. functionMap := make(functionMap)
  274. for i, n := range g.Nodes {
  275. f := functionMap.FindOrAdd(n.Info)
  276. flat, cum := n.FlatValue(), n.CumValue()
  277. l := &profile.Location{
  278. ID: uint64(i + 1),
  279. Address: n.Info.Address,
  280. Line: []profile.Line{
  281. {
  282. Line: int64(n.Info.Lineno),
  283. Function: f,
  284. },
  285. },
  286. }
  287. fv, _ := measurement.Scale(flat, o.SampleUnit, o.OutputUnit)
  288. cv, _ := measurement.Scale(cum, o.SampleUnit, o.OutputUnit)
  289. s := &profile.Sample{
  290. Location: []*profile.Location{l},
  291. Value: []int64{int64(cv), int64(fv)},
  292. }
  293. out.Function = append(out.Function, f)
  294. out.Location = append(out.Location, l)
  295. out.Sample = append(out.Sample, s)
  296. }
  297. return out.Write(w)
  298. }
  299. type functionMap map[string]*profile.Function
  300. func (fm functionMap) FindOrAdd(ni graph.NodeInfo) *profile.Function {
  301. fName := fmt.Sprintf("%q%q%q%d", ni.Name, ni.OrigName, ni.File, ni.StartLine)
  302. if f := fm[fName]; f != nil {
  303. return f
  304. }
  305. f := &profile.Function{
  306. ID: uint64(len(fm) + 1),
  307. Name: ni.Name,
  308. SystemName: ni.OrigName,
  309. Filename: ni.File,
  310. StartLine: int64(ni.StartLine),
  311. }
  312. fm[fName] = f
  313. return f
  314. }
  315. // printAssembly prints an annotated assembly listing.
  316. func printAssembly(w io.Writer, rpt *Report, obj plugin.ObjTool) error {
  317. return PrintAssembly(w, rpt, obj, -1)
  318. }
  319. // PrintAssembly prints annotated disasssembly of rpt to w.
  320. func PrintAssembly(w io.Writer, rpt *Report, obj plugin.ObjTool, maxFuncs int) error {
  321. o := rpt.options
  322. prof := rpt.prof
  323. g := rpt.newGraph(nil)
  324. // If the regexp source can be parsed as an address, also match
  325. // functions that land on that address.
  326. var address *uint64
  327. if hex, err := strconv.ParseUint(o.Symbol.String(), 0, 64); err == nil {
  328. address = &hex
  329. }
  330. fmt.Fprintln(w, "Total:", rpt.formatValue(rpt.total))
  331. symbols := symbolsFromBinaries(prof, g, o.Symbol, address, obj)
  332. symNodes := nodesPerSymbol(g.Nodes, symbols)
  333. // Sort for printing.
  334. var syms []*objSymbol
  335. for s := range symNodes {
  336. syms = append(syms, s)
  337. }
  338. byName := func(a, b *objSymbol) bool {
  339. if na, nb := a.sym.Name[0], b.sym.Name[0]; na != nb {
  340. return na < nb
  341. }
  342. return a.sym.Start < b.sym.Start
  343. }
  344. if maxFuncs < 0 {
  345. sort.Sort(orderSyms{syms, byName})
  346. } else {
  347. byFlatSum := func(a, b *objSymbol) bool {
  348. suma, _ := symNodes[a].Sum()
  349. sumb, _ := symNodes[b].Sum()
  350. if suma != sumb {
  351. return suma > sumb
  352. }
  353. return byName(a, b)
  354. }
  355. sort.Sort(orderSyms{syms, byFlatSum})
  356. if len(syms) > maxFuncs {
  357. syms = syms[:maxFuncs]
  358. }
  359. }
  360. // Correlate the symbols from the binary with the profile samples.
  361. for _, s := range syms {
  362. sns := symNodes[s]
  363. // Gather samples for this symbol.
  364. flatSum, cumSum := sns.Sum()
  365. // Get the function assembly.
  366. insts, err := obj.Disasm(s.sym.File, s.sym.Start, s.sym.End)
  367. if err != nil {
  368. return err
  369. }
  370. ns := annotateAssembly(insts, sns, s.base)
  371. fmt.Fprintf(w, "ROUTINE ======================== %s\n", s.sym.Name[0])
  372. for _, name := range s.sym.Name[1:] {
  373. fmt.Fprintf(w, " AKA ======================== %s\n", name)
  374. }
  375. fmt.Fprintf(w, "%10s %10s (flat, cum) %s of Total\n",
  376. rpt.formatValue(flatSum), rpt.formatValue(cumSum),
  377. percentage(cumSum, rpt.total))
  378. function, file, line := "", "", 0
  379. for _, n := range ns {
  380. locStr := ""
  381. // Skip loc information if it hasn't changed from previous instruction.
  382. if n.function != function || n.file != file || n.line != line {
  383. function, file, line = n.function, n.file, n.line
  384. if n.function != "" {
  385. locStr = n.function + " "
  386. }
  387. if n.file != "" {
  388. locStr += n.file
  389. if n.line != 0 {
  390. locStr += fmt.Sprintf(":%d", n.line)
  391. }
  392. }
  393. }
  394. switch {
  395. case locStr == "":
  396. // No location info, just print the instruction.
  397. fmt.Fprintf(w, "%10s %10s %10x: %s\n",
  398. valueOrDot(n.flatValue(), rpt),
  399. valueOrDot(n.cumValue(), rpt),
  400. n.address, n.instruction,
  401. )
  402. case len(n.instruction) < 40:
  403. // Short instruction, print loc on the same line.
  404. fmt.Fprintf(w, "%10s %10s %10x: %-40s;%s\n",
  405. valueOrDot(n.flatValue(), rpt),
  406. valueOrDot(n.cumValue(), rpt),
  407. n.address, n.instruction,
  408. locStr,
  409. )
  410. default:
  411. // Long instruction, print loc on a separate line.
  412. fmt.Fprintf(w, "%74s;%s\n", "", locStr)
  413. fmt.Fprintf(w, "%10s %10s %10x: %s\n",
  414. valueOrDot(n.flatValue(), rpt),
  415. valueOrDot(n.cumValue(), rpt),
  416. n.address, n.instruction,
  417. )
  418. }
  419. }
  420. }
  421. return nil
  422. }
  423. // symbolsFromBinaries examines the binaries listed on the profile
  424. // that have associated samples, and identifies symbols matching rx.
  425. func symbolsFromBinaries(prof *profile.Profile, g *graph.Graph, rx *regexp.Regexp, address *uint64, obj plugin.ObjTool) []*objSymbol {
  426. hasSamples := make(map[string]bool)
  427. // Only examine mappings that have samples that match the
  428. // regexp. This is an optimization to speed up pprof.
  429. for _, n := range g.Nodes {
  430. if name := n.Info.PrintableName(); rx.MatchString(name) && n.Info.Objfile != "" {
  431. hasSamples[n.Info.Objfile] = true
  432. }
  433. }
  434. // Walk all mappings looking for matching functions with samples.
  435. var objSyms []*objSymbol
  436. for _, m := range prof.Mapping {
  437. if !hasSamples[m.File] {
  438. if address == nil || !(m.Start <= *address && *address <= m.Limit) {
  439. continue
  440. }
  441. }
  442. f, err := obj.Open(m.File, m.Start, m.Limit, m.Offset)
  443. if err != nil {
  444. fmt.Printf("%v\n", err)
  445. continue
  446. }
  447. // Find symbols in this binary matching the user regexp.
  448. var addr uint64
  449. if address != nil {
  450. addr = *address
  451. }
  452. msyms, err := f.Symbols(rx, addr)
  453. base := f.Base()
  454. f.Close()
  455. if err != nil {
  456. continue
  457. }
  458. for _, ms := range msyms {
  459. objSyms = append(objSyms,
  460. &objSymbol{
  461. sym: ms,
  462. base: base,
  463. },
  464. )
  465. }
  466. }
  467. return objSyms
  468. }
  469. // objSym represents a symbol identified from a binary. It includes
  470. // the SymbolInfo from the disasm package and the base that must be
  471. // added to correspond to sample addresses
  472. type objSymbol struct {
  473. sym *plugin.Sym
  474. base uint64
  475. }
  476. // orderSyms is a wrapper type to sort []*objSymbol by a supplied comparator.
  477. type orderSyms struct {
  478. v []*objSymbol
  479. less func(a, b *objSymbol) bool
  480. }
  481. func (o orderSyms) Len() int { return len(o.v) }
  482. func (o orderSyms) Less(i, j int) bool { return o.less(o.v[i], o.v[j]) }
  483. func (o orderSyms) Swap(i, j int) { o.v[i], o.v[j] = o.v[j], o.v[i] }
  484. // nodesPerSymbol classifies nodes into a group of symbols.
  485. func nodesPerSymbol(ns graph.Nodes, symbols []*objSymbol) map[*objSymbol]graph.Nodes {
  486. symNodes := make(map[*objSymbol]graph.Nodes)
  487. for _, s := range symbols {
  488. // Gather samples for this symbol.
  489. for _, n := range ns {
  490. address := n.Info.Address - s.base
  491. if address >= s.sym.Start && address < s.sym.End {
  492. symNodes[s] = append(symNodes[s], n)
  493. }
  494. }
  495. }
  496. return symNodes
  497. }
  498. type assemblyInstruction struct {
  499. address uint64
  500. instruction string
  501. function string
  502. file string
  503. line int
  504. flat, cum int64
  505. flatDiv, cumDiv int64
  506. startsBlock bool
  507. }
  508. func (a *assemblyInstruction) flatValue() int64 {
  509. if a.flatDiv != 0 {
  510. return a.flat / a.flatDiv
  511. }
  512. return a.flat
  513. }
  514. func (a *assemblyInstruction) cumValue() int64 {
  515. if a.cumDiv != 0 {
  516. return a.cum / a.cumDiv
  517. }
  518. return a.cum
  519. }
  520. // annotateAssembly annotates a set of assembly instructions with a
  521. // set of samples. It returns a set of nodes to display. base is an
  522. // offset to adjust the sample addresses.
  523. func annotateAssembly(insts []plugin.Inst, samples graph.Nodes, base uint64) []assemblyInstruction {
  524. // Add end marker to simplify printing loop.
  525. insts = append(insts, plugin.Inst{
  526. Addr: ^uint64(0),
  527. })
  528. // Ensure samples are sorted by address.
  529. samples.Sort(graph.AddressOrder)
  530. s := 0
  531. asm := make([]assemblyInstruction, 0, len(insts))
  532. for ix, in := range insts[:len(insts)-1] {
  533. n := assemblyInstruction{
  534. address: in.Addr,
  535. instruction: in.Text,
  536. function: in.Function,
  537. line: in.Line,
  538. }
  539. if in.File != "" {
  540. n.file = filepath.Base(in.File)
  541. }
  542. // Sum all the samples until the next instruction (to account
  543. // for samples attributed to the middle of an instruction).
  544. for next := insts[ix+1].Addr; s < len(samples) && samples[s].Info.Address-base < next; s++ {
  545. sample := samples[s]
  546. n.flatDiv += sample.FlatDiv
  547. n.flat += sample.Flat
  548. n.cumDiv += sample.CumDiv
  549. n.cum += sample.Cum
  550. if f := sample.Info.File; f != "" && n.file == "" {
  551. n.file = filepath.Base(f)
  552. }
  553. if ln := sample.Info.Lineno; ln != 0 && n.line == 0 {
  554. n.line = ln
  555. }
  556. if f := sample.Info.Name; f != "" && n.function == "" {
  557. n.function = f
  558. }
  559. }
  560. asm = append(asm, n)
  561. }
  562. return asm
  563. }
  564. // valueOrDot formats a value according to a report, intercepting zero
  565. // values.
  566. func valueOrDot(value int64, rpt *Report) string {
  567. if value == 0 {
  568. return "."
  569. }
  570. return rpt.formatValue(value)
  571. }
  572. // printTags collects all tags referenced in the profile and prints
  573. // them in a sorted table.
  574. func printTags(w io.Writer, rpt *Report) error {
  575. p := rpt.prof
  576. o := rpt.options
  577. formatTag := func(v int64, key string) string {
  578. return measurement.ScaledLabel(v, key, o.OutputUnit)
  579. }
  580. // Hashtable to keep accumulate tags as key,value,count.
  581. tagMap := make(map[string]map[string]int64)
  582. for _, s := range p.Sample {
  583. for key, vals := range s.Label {
  584. for _, val := range vals {
  585. valueMap, ok := tagMap[key]
  586. if !ok {
  587. valueMap = make(map[string]int64)
  588. tagMap[key] = valueMap
  589. }
  590. valueMap[val] += o.SampleValue(s.Value)
  591. }
  592. }
  593. for key, vals := range s.NumLabel {
  594. unit := o.NumLabelUnits[key]
  595. for _, nval := range vals {
  596. val := formatTag(nval, unit)
  597. valueMap, ok := tagMap[key]
  598. if !ok {
  599. valueMap = make(map[string]int64)
  600. tagMap[key] = valueMap
  601. }
  602. valueMap[val] += o.SampleValue(s.Value)
  603. }
  604. }
  605. }
  606. tagKeys := make([]*graph.Tag, 0, len(tagMap))
  607. for key := range tagMap {
  608. tagKeys = append(tagKeys, &graph.Tag{Name: key})
  609. }
  610. tabw := tabwriter.NewWriter(w, 0, 0, 1, ' ', tabwriter.AlignRight)
  611. for _, tagKey := range graph.SortTags(tagKeys, true) {
  612. var total int64
  613. key := tagKey.Name
  614. tags := make([]*graph.Tag, 0, len(tagMap[key]))
  615. for t, c := range tagMap[key] {
  616. total += c
  617. tags = append(tags, &graph.Tag{Name: t, Flat: c})
  618. }
  619. f, u := measurement.Scale(total, o.SampleUnit, o.OutputUnit)
  620. fmt.Fprintf(tabw, "%s:\t Total %.1f%s\n", key, f, u)
  621. for _, t := range graph.SortTags(tags, true) {
  622. f, u := measurement.Scale(t.FlatValue(), o.SampleUnit, o.OutputUnit)
  623. if total > 0 {
  624. fmt.Fprintf(tabw, " \t%.1f%s (%s):\t %s\n", f, u, percentage(t.FlatValue(), total), t.Name)
  625. } else {
  626. fmt.Fprintf(tabw, " \t%.1f%s:\t %s\n", f, u, t.Name)
  627. }
  628. }
  629. fmt.Fprintln(tabw)
  630. }
  631. return tabw.Flush()
  632. }
  633. // printComments prints all freeform comments in the profile.
  634. func printComments(w io.Writer, rpt *Report) error {
  635. p := rpt.prof
  636. for _, c := range p.Comments {
  637. fmt.Fprintln(w, c)
  638. }
  639. return nil
  640. }
  641. // TextItem holds a single text report entry.
  642. type TextItem struct {
  643. Name string
  644. InlineLabel string // Not empty if inlined
  645. Flat, Cum int64 // Raw values
  646. FlatFormat, CumFormat string // Formatted values
  647. }
  648. // TextItems returns a list of text items from the report and a list
  649. // of labels that describe the report.
  650. func TextItems(rpt *Report) ([]TextItem, []string) {
  651. g, origCount, droppedNodes, _ := rpt.newTrimmedGraph()
  652. rpt.selectOutputUnit(g)
  653. labels := reportLabels(rpt, g, origCount, droppedNodes, 0, false)
  654. var items []TextItem
  655. var flatSum int64
  656. for _, n := range g.Nodes {
  657. name, flat, cum := n.Info.PrintableName(), n.FlatValue(), n.CumValue()
  658. var inline, noinline bool
  659. for _, e := range n.In {
  660. if e.Inline {
  661. inline = true
  662. } else {
  663. noinline = true
  664. }
  665. }
  666. var inl string
  667. if inline {
  668. if noinline {
  669. inl = "(partial-inline)"
  670. } else {
  671. inl = "(inline)"
  672. }
  673. }
  674. flatSum += flat
  675. items = append(items, TextItem{
  676. Name: name,
  677. InlineLabel: inl,
  678. Flat: flat,
  679. Cum: cum,
  680. FlatFormat: rpt.formatValue(flat),
  681. CumFormat: rpt.formatValue(cum),
  682. })
  683. }
  684. return items, labels
  685. }
  686. // printText prints a flat text report for a profile.
  687. func printText(w io.Writer, rpt *Report) error {
  688. items, labels := TextItems(rpt)
  689. fmt.Fprintln(w, strings.Join(labels, "\n"))
  690. fmt.Fprintf(w, "%10s %5s%% %5s%% %10s %5s%%\n",
  691. "flat", "flat", "sum", "cum", "cum")
  692. var flatSum int64
  693. for _, item := range items {
  694. inl := item.InlineLabel
  695. if inl != "" {
  696. inl = " " + inl
  697. }
  698. flatSum += item.Flat
  699. fmt.Fprintf(w, "%10s %s %s %10s %s %s%s\n",
  700. item.FlatFormat, percentage(item.Flat, rpt.total),
  701. percentage(flatSum, rpt.total),
  702. item.CumFormat, percentage(item.Cum, rpt.total),
  703. item.Name, inl)
  704. }
  705. return nil
  706. }
  707. // printTraces prints all traces from a profile.
  708. func printTraces(w io.Writer, rpt *Report) error {
  709. fmt.Fprintln(w, strings.Join(ProfileLabels(rpt), "\n"))
  710. prof := rpt.prof
  711. o := rpt.options
  712. const separator = "-----------+-------------------------------------------------------"
  713. _, locations := graph.CreateNodes(prof, &graph.Options{})
  714. for _, sample := range prof.Sample {
  715. var stack graph.Nodes
  716. for _, loc := range sample.Location {
  717. id := loc.ID
  718. stack = append(stack, locations[id]...)
  719. }
  720. if len(stack) == 0 {
  721. continue
  722. }
  723. fmt.Fprintln(w, separator)
  724. // Print any text labels for the sample.
  725. var labels []string
  726. for s, vs := range sample.Label {
  727. labels = append(labels, fmt.Sprintf("%10s: %s\n", s, strings.Join(vs, " ")))
  728. }
  729. sort.Strings(labels)
  730. fmt.Fprint(w, strings.Join(labels, ""))
  731. // Print any numeric labels for the sample
  732. var numLabels []string
  733. for key, vals := range sample.NumLabel {
  734. unit := o.NumLabelUnits[key]
  735. numValues := make([]string, len(vals))
  736. for i, vv := range vals {
  737. numValues[i] = measurement.Label(vv, unit)
  738. }
  739. numLabels = append(numLabels, fmt.Sprintf("%10s: %s\n", key, strings.Join(numValues, " ")))
  740. }
  741. sort.Strings(numLabels)
  742. fmt.Fprint(w, strings.Join(numLabels, ""))
  743. var d, v int64
  744. v = o.SampleValue(sample.Value)
  745. if o.SampleMeanDivisor != nil {
  746. d = o.SampleMeanDivisor(sample.Value)
  747. }
  748. // Print call stack.
  749. if d != 0 {
  750. v = v / d
  751. }
  752. fmt.Fprintf(w, "%10s %s\n",
  753. rpt.formatValue(v), stack[0].Info.PrintableName())
  754. for _, s := range stack[1:] {
  755. fmt.Fprintf(w, "%10s %s\n", "", s.Info.PrintableName())
  756. }
  757. }
  758. fmt.Fprintln(w, separator)
  759. return nil
  760. }
  761. // printCallgrind prints a graph for a profile on callgrind format.
  762. func printCallgrind(w io.Writer, rpt *Report) error {
  763. o := rpt.options
  764. rpt.options.NodeFraction = 0
  765. rpt.options.EdgeFraction = 0
  766. rpt.options.NodeCount = 0
  767. g, _, _, _ := rpt.newTrimmedGraph()
  768. rpt.selectOutputUnit(g)
  769. nodeNames := getDisambiguatedNames(g)
  770. fmt.Fprintln(w, "positions: instr line")
  771. fmt.Fprintln(w, "events:", o.SampleType+"("+o.OutputUnit+")")
  772. objfiles := make(map[string]int)
  773. files := make(map[string]int)
  774. names := make(map[string]int)
  775. // prevInfo points to the previous NodeInfo.
  776. // It is used to group cost lines together as much as possible.
  777. var prevInfo *graph.NodeInfo
  778. for _, n := range g.Nodes {
  779. if prevInfo == nil || n.Info.Objfile != prevInfo.Objfile || n.Info.File != prevInfo.File || n.Info.Name != prevInfo.Name {
  780. fmt.Fprintln(w)
  781. fmt.Fprintln(w, "ob="+callgrindName(objfiles, n.Info.Objfile))
  782. fmt.Fprintln(w, "fl="+callgrindName(files, n.Info.File))
  783. fmt.Fprintln(w, "fn="+callgrindName(names, n.Info.Name))
  784. }
  785. addr := callgrindAddress(prevInfo, n.Info.Address)
  786. sv, _ := measurement.Scale(n.FlatValue(), o.SampleUnit, o.OutputUnit)
  787. fmt.Fprintf(w, "%s %d %d\n", addr, n.Info.Lineno, int64(sv))
  788. // Print outgoing edges.
  789. for _, out := range n.Out.Sort() {
  790. c, _ := measurement.Scale(out.Weight, o.SampleUnit, o.OutputUnit)
  791. callee := out.Dest
  792. fmt.Fprintln(w, "cfl="+callgrindName(files, callee.Info.File))
  793. fmt.Fprintln(w, "cfn="+callgrindName(names, nodeNames[callee]))
  794. // pprof doesn't have a flat weight for a call, leave as 0.
  795. fmt.Fprintf(w, "calls=0 %s %d\n", callgrindAddress(prevInfo, callee.Info.Address), callee.Info.Lineno)
  796. // TODO: This address may be in the middle of a call
  797. // instruction. It would be best to find the beginning
  798. // of the instruction, but the tools seem to handle
  799. // this OK.
  800. fmt.Fprintf(w, "* * %d\n", int64(c))
  801. }
  802. prevInfo = &n.Info
  803. }
  804. return nil
  805. }
  806. // getDisambiguatedNames returns a map from each node in the graph to
  807. // the name to use in the callgrind output. Callgrind merges all
  808. // functions with the same [file name, function name]. Add a [%d/n]
  809. // suffix to disambiguate nodes with different values of
  810. // node.Function, which we want to keep separate. In particular, this
  811. // affects graphs created with --call_tree, where nodes from different
  812. // contexts are associated to different Functions.
  813. func getDisambiguatedNames(g *graph.Graph) map[*graph.Node]string {
  814. nodeName := make(map[*graph.Node]string, len(g.Nodes))
  815. type names struct {
  816. file, function string
  817. }
  818. // nameFunctionIndex maps the callgrind names (filename, function)
  819. // to the node.Function values found for that name, and each
  820. // node.Function value to a sequential index to be used on the
  821. // disambiguated name.
  822. nameFunctionIndex := make(map[names]map[*graph.Node]int)
  823. for _, n := range g.Nodes {
  824. nm := names{n.Info.File, n.Info.Name}
  825. p, ok := nameFunctionIndex[nm]
  826. if !ok {
  827. p = make(map[*graph.Node]int)
  828. nameFunctionIndex[nm] = p
  829. }
  830. if _, ok := p[n.Function]; !ok {
  831. p[n.Function] = len(p)
  832. }
  833. }
  834. for _, n := range g.Nodes {
  835. nm := names{n.Info.File, n.Info.Name}
  836. nodeName[n] = n.Info.Name
  837. if p := nameFunctionIndex[nm]; len(p) > 1 {
  838. // If there is more than one function, add suffix to disambiguate.
  839. nodeName[n] += fmt.Sprintf(" [%d/%d]", p[n.Function]+1, len(p))
  840. }
  841. }
  842. return nodeName
  843. }
  844. // callgrindName implements the callgrind naming compression scheme.
  845. // For names not previously seen returns "(N) name", where N is a
  846. // unique index. For names previously seen returns "(N)" where N is
  847. // the index returned the first time.
  848. func callgrindName(names map[string]int, name string) string {
  849. if name == "" {
  850. return ""
  851. }
  852. if id, ok := names[name]; ok {
  853. return fmt.Sprintf("(%d)", id)
  854. }
  855. id := len(names) + 1
  856. names[name] = id
  857. return fmt.Sprintf("(%d) %s", id, name)
  858. }
  859. // callgrindAddress implements the callgrind subposition compression scheme if
  860. // possible. If prevInfo != nil, it contains the previous address. The current
  861. // address can be given relative to the previous address, with an explicit +/-
  862. // to indicate it is relative, or * for the same address.
  863. func callgrindAddress(prevInfo *graph.NodeInfo, curr uint64) string {
  864. abs := fmt.Sprintf("%#x", curr)
  865. if prevInfo == nil {
  866. return abs
  867. }
  868. prev := prevInfo.Address
  869. if prev == curr {
  870. return "*"
  871. }
  872. diff := int64(curr - prev)
  873. relative := fmt.Sprintf("%+d", diff)
  874. // Only bother to use the relative address if it is actually shorter.
  875. if len(relative) < len(abs) {
  876. return relative
  877. }
  878. return abs
  879. }
  880. // printTree prints a tree-based report in text form.
  881. func printTree(w io.Writer, rpt *Report) error {
  882. const separator = "----------------------------------------------------------+-------------"
  883. const legend = " flat flat% sum% cum cum% calls calls% + context "
  884. g, origCount, droppedNodes, _ := rpt.newTrimmedGraph()
  885. rpt.selectOutputUnit(g)
  886. fmt.Fprintln(w, strings.Join(reportLabels(rpt, g, origCount, droppedNodes, 0, false), "\n"))
  887. fmt.Fprintln(w, separator)
  888. fmt.Fprintln(w, legend)
  889. var flatSum int64
  890. rx := rpt.options.Symbol
  891. for _, n := range g.Nodes {
  892. name, flat, cum := n.Info.PrintableName(), n.FlatValue(), n.CumValue()
  893. // Skip any entries that do not match the regexp (for the "peek" command).
  894. if rx != nil && !rx.MatchString(name) {
  895. continue
  896. }
  897. fmt.Fprintln(w, separator)
  898. // Print incoming edges.
  899. inEdges := n.In.Sort()
  900. for _, in := range inEdges {
  901. var inline string
  902. if in.Inline {
  903. inline = " (inline)"
  904. }
  905. fmt.Fprintf(w, "%50s %s | %s%s\n", rpt.formatValue(in.Weight),
  906. percentage(in.Weight, cum), in.Src.Info.PrintableName(), inline)
  907. }
  908. // Print current node.
  909. flatSum += flat
  910. fmt.Fprintf(w, "%10s %s %s %10s %s | %s\n",
  911. rpt.formatValue(flat),
  912. percentage(flat, rpt.total),
  913. percentage(flatSum, rpt.total),
  914. rpt.formatValue(cum),
  915. percentage(cum, rpt.total),
  916. name)
  917. // Print outgoing edges.
  918. outEdges := n.Out.Sort()
  919. for _, out := range outEdges {
  920. var inline string
  921. if out.Inline {
  922. inline = " (inline)"
  923. }
  924. fmt.Fprintf(w, "%50s %s | %s%s\n", rpt.formatValue(out.Weight),
  925. percentage(out.Weight, cum), out.Dest.Info.PrintableName(), inline)
  926. }
  927. }
  928. if len(g.Nodes) > 0 {
  929. fmt.Fprintln(w, separator)
  930. }
  931. return nil
  932. }
  933. // GetDOT returns a graph suitable for dot processing along with some
  934. // configuration information.
  935. func GetDOT(rpt *Report) (*graph.Graph, *graph.DotConfig) {
  936. g, origCount, droppedNodes, droppedEdges := rpt.newTrimmedGraph()
  937. rpt.selectOutputUnit(g)
  938. labels := reportLabels(rpt, g, origCount, droppedNodes, droppedEdges, true)
  939. c := &graph.DotConfig{
  940. Title: rpt.options.Title,
  941. Labels: labels,
  942. FormatValue: rpt.formatValue,
  943. Total: rpt.total,
  944. }
  945. return g, c
  946. }
  947. // printDOT prints an annotated callgraph in DOT format.
  948. func printDOT(w io.Writer, rpt *Report) error {
  949. g, c := GetDOT(rpt)
  950. graph.ComposeDot(w, g, &graph.DotAttributes{}, c)
  951. return nil
  952. }
  953. // percentage computes the percentage of total of a value, and encodes
  954. // it as a string. At least two digits of precision are printed.
  955. func percentage(value, total int64) string {
  956. var ratio float64
  957. if total != 0 {
  958. ratio = math.Abs(float64(value)/float64(total)) * 100
  959. }
  960. switch {
  961. case math.Abs(ratio) >= 99.95 && math.Abs(ratio) <= 100.05:
  962. return " 100%"
  963. case math.Abs(ratio) >= 1.0:
  964. return fmt.Sprintf("%5.2f%%", ratio)
  965. default:
  966. return fmt.Sprintf("%5.2g%%", ratio)
  967. }
  968. }
  969. // ProfileLabels returns printable labels for a profile.
  970. func ProfileLabels(rpt *Report) []string {
  971. label := []string{}
  972. prof := rpt.prof
  973. o := rpt.options
  974. if len(prof.Mapping) > 0 {
  975. if prof.Mapping[0].File != "" {
  976. label = append(label, "File: "+filepath.Base(prof.Mapping[0].File))
  977. }
  978. if prof.Mapping[0].BuildID != "" {
  979. label = append(label, "Build ID: "+prof.Mapping[0].BuildID)
  980. }
  981. }
  982. // Only include comments that do not start with '#'.
  983. for _, c := range prof.Comments {
  984. if !strings.HasPrefix(c, "#") {
  985. label = append(label, c)
  986. }
  987. }
  988. if o.SampleType != "" {
  989. label = append(label, "Type: "+o.SampleType)
  990. }
  991. if prof.TimeNanos != 0 {
  992. const layout = "Jan 2, 2006 at 3:04pm (MST)"
  993. label = append(label, "Time: "+time.Unix(0, prof.TimeNanos).Format(layout))
  994. }
  995. if prof.DurationNanos != 0 {
  996. duration := measurement.Label(prof.DurationNanos, "nanoseconds")
  997. totalNanos, totalUnit := measurement.Scale(rpt.total, o.SampleUnit, "nanoseconds")
  998. var ratio string
  999. if totalUnit == "ns" && totalNanos != 0 {
  1000. ratio = "(" + percentage(int64(totalNanos), prof.DurationNanos) + ")"
  1001. }
  1002. label = append(label, fmt.Sprintf("Duration: %s, Total samples = %s %s", duration, rpt.formatValue(rpt.total), ratio))
  1003. }
  1004. return label
  1005. }
  1006. // reportLabels returns printable labels for a report. Includes
  1007. // profileLabels.
  1008. func reportLabels(rpt *Report, g *graph.Graph, origCount, droppedNodes, droppedEdges int, fullHeaders bool) []string {
  1009. nodeFraction := rpt.options.NodeFraction
  1010. edgeFraction := rpt.options.EdgeFraction
  1011. nodeCount := len(g.Nodes)
  1012. var label []string
  1013. if len(rpt.options.ProfileLabels) > 0 {
  1014. label = append(label, rpt.options.ProfileLabels...)
  1015. } else if fullHeaders || !rpt.options.CompactLabels {
  1016. label = ProfileLabels(rpt)
  1017. }
  1018. var flatSum int64
  1019. for _, n := range g.Nodes {
  1020. flatSum = flatSum + n.FlatValue()
  1021. }
  1022. if len(rpt.options.ActiveFilters) > 0 {
  1023. activeFilters := legendActiveFilters(rpt.options.ActiveFilters)
  1024. label = append(label, activeFilters...)
  1025. }
  1026. label = append(label, fmt.Sprintf("Showing nodes accounting for %s, %s of %s total", rpt.formatValue(flatSum), strings.TrimSpace(percentage(flatSum, rpt.total)), rpt.formatValue(rpt.total)))
  1027. if rpt.total != 0 {
  1028. if droppedNodes > 0 {
  1029. label = append(label, genLabel(droppedNodes, "node", "cum",
  1030. rpt.formatValue(abs64(int64(float64(rpt.total)*nodeFraction)))))
  1031. }
  1032. if droppedEdges > 0 {
  1033. label = append(label, genLabel(droppedEdges, "edge", "freq",
  1034. rpt.formatValue(abs64(int64(float64(rpt.total)*edgeFraction)))))
  1035. }
  1036. if nodeCount > 0 && nodeCount < origCount {
  1037. label = append(label, fmt.Sprintf("Showing top %d nodes out of %d",
  1038. nodeCount, origCount))
  1039. }
  1040. }
  1041. return label
  1042. }
  1043. func legendActiveFilters(activeFilters []string) []string {
  1044. legendActiveFilters := make([]string, len(activeFilters)+1)
  1045. legendActiveFilters[0] = "Active filters:"
  1046. for i, s := range activeFilters {
  1047. if len(s) > 80 {
  1048. s = s[:80] + "…"
  1049. }
  1050. legendActiveFilters[i+1] = " " + s
  1051. }
  1052. return legendActiveFilters
  1053. }
  1054. func genLabel(d int, n, l, f string) string {
  1055. if d > 1 {
  1056. n = n + "s"
  1057. }
  1058. return fmt.Sprintf("Dropped %d %s (%s <= %s)", d, n, l, f)
  1059. }
  1060. // New builds a new report indexing the sample values interpreting the
  1061. // samples with the provided function.
  1062. func New(prof *profile.Profile, o *Options) *Report {
  1063. format := func(v int64) string {
  1064. if r := o.Ratio; r > 0 && r != 1 {
  1065. fv := float64(v) * r
  1066. v = int64(fv)
  1067. }
  1068. return measurement.ScaledLabel(v, o.SampleUnit, o.OutputUnit)
  1069. }
  1070. return &Report{prof, computeTotal(prof, o.SampleValue, o.SampleMeanDivisor, !o.PositivePercentages),
  1071. o, format}
  1072. }
  1073. // NewDefault builds a new report indexing the last sample value
  1074. // available.
  1075. func NewDefault(prof *profile.Profile, options Options) *Report {
  1076. index := len(prof.SampleType) - 1
  1077. o := &options
  1078. if o.Title == "" && len(prof.Mapping) > 0 && prof.Mapping[0].File != "" {
  1079. o.Title = filepath.Base(prof.Mapping[0].File)
  1080. }
  1081. o.SampleType = prof.SampleType[index].Type
  1082. o.SampleUnit = strings.ToLower(prof.SampleType[index].Unit)
  1083. o.SampleValue = func(v []int64) int64 {
  1084. return v[index]
  1085. }
  1086. return New(prof, o)
  1087. }
  1088. // computeTotal computes the sum of all sample values. This will be
  1089. // used to compute percentages. If includeNegative is set, use use
  1090. // absolute values to provide a meaningful percentage for both
  1091. // negative and positive values. Otherwise only use positive values,
  1092. // which is useful when comparing profiles from different jobs.
  1093. func computeTotal(prof *profile.Profile, value, meanDiv func(v []int64) int64, includeNegative bool) int64 {
  1094. var div, ret int64
  1095. for _, sample := range prof.Sample {
  1096. var d, v int64
  1097. v = value(sample.Value)
  1098. if meanDiv != nil {
  1099. d = meanDiv(sample.Value)
  1100. }
  1101. if v >= 0 {
  1102. ret += v
  1103. div += d
  1104. } else if includeNegative {
  1105. ret -= v
  1106. div += d
  1107. }
  1108. }
  1109. if div != 0 {
  1110. return ret / div
  1111. }
  1112. return ret
  1113. }
  1114. // Report contains the data and associated routines to extract a
  1115. // report from a profile.
  1116. type Report struct {
  1117. prof *profile.Profile
  1118. total int64
  1119. options *Options
  1120. formatValue func(int64) string
  1121. }
  1122. // Total returns the total number of samples in a report.
  1123. func (rpt *Report) Total() int64 { return rpt.total }
  1124. func abs64(i int64) int64 {
  1125. if i < 0 {
  1126. return -i
  1127. }
  1128. return i
  1129. }