暂无描述

report.go 36KB

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