No Description

report.go 35KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277
  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. file: f,
  464. },
  465. )
  466. }
  467. }
  468. return objSyms
  469. }
  470. // objSym represents a symbol identified from a binary. It includes
  471. // the SymbolInfo from the disasm package and the base that must be
  472. // added to correspond to sample addresses
  473. type objSymbol struct {
  474. sym *plugin.Sym
  475. base uint64
  476. file plugin.ObjFile
  477. }
  478. // orderSyms is a wrapper type to sort []*objSymbol by a supplied comparator.
  479. type orderSyms struct {
  480. v []*objSymbol
  481. less func(a, b *objSymbol) bool
  482. }
  483. func (o orderSyms) Len() int { return len(o.v) }
  484. func (o orderSyms) Less(i, j int) bool { return o.less(o.v[i], o.v[j]) }
  485. func (o orderSyms) Swap(i, j int) { o.v[i], o.v[j] = o.v[j], o.v[i] }
  486. // nodesPerSymbol classifies nodes into a group of symbols.
  487. func nodesPerSymbol(ns graph.Nodes, symbols []*objSymbol) map[*objSymbol]graph.Nodes {
  488. symNodes := make(map[*objSymbol]graph.Nodes)
  489. for _, s := range symbols {
  490. // Gather samples for this symbol.
  491. for _, n := range ns {
  492. address := n.Info.Address - s.base
  493. if address >= s.sym.Start && address < s.sym.End {
  494. symNodes[s] = append(symNodes[s], n)
  495. }
  496. }
  497. }
  498. return symNodes
  499. }
  500. type assemblyInstruction struct {
  501. address uint64
  502. instruction string
  503. function string
  504. file string
  505. line int
  506. flat, cum int64
  507. flatDiv, cumDiv int64
  508. startsBlock bool
  509. inlineCalls []callID
  510. }
  511. type callID struct {
  512. file string
  513. line int
  514. }
  515. func (a *assemblyInstruction) flatValue() int64 {
  516. if a.flatDiv != 0 {
  517. return a.flat / a.flatDiv
  518. }
  519. return a.flat
  520. }
  521. func (a *assemblyInstruction) cumValue() int64 {
  522. if a.cumDiv != 0 {
  523. return a.cum / a.cumDiv
  524. }
  525. return a.cum
  526. }
  527. // annotateAssembly annotates a set of assembly instructions with a
  528. // set of samples. It returns a set of nodes to display. base is an
  529. // offset to adjust the sample addresses.
  530. func annotateAssembly(insts []plugin.Inst, samples graph.Nodes, base uint64) []assemblyInstruction {
  531. // Add end marker to simplify printing loop.
  532. insts = append(insts, plugin.Inst{
  533. Addr: ^uint64(0),
  534. })
  535. // Ensure samples are sorted by address.
  536. samples.Sort(graph.AddressOrder)
  537. s := 0
  538. asm := make([]assemblyInstruction, 0, len(insts))
  539. for ix, in := range insts[:len(insts)-1] {
  540. n := assemblyInstruction{
  541. address: in.Addr,
  542. instruction: in.Text,
  543. function: in.Function,
  544. line: in.Line,
  545. }
  546. if in.File != "" {
  547. n.file = filepath.Base(in.File)
  548. }
  549. // Sum all the samples until the next instruction (to account
  550. // for samples attributed to the middle of an instruction).
  551. for next := insts[ix+1].Addr; s < len(samples) && samples[s].Info.Address-base < next; s++ {
  552. sample := samples[s]
  553. n.flatDiv += sample.FlatDiv
  554. n.flat += sample.Flat
  555. n.cumDiv += sample.CumDiv
  556. n.cum += sample.Cum
  557. if f := sample.Info.File; f != "" && n.file == "" {
  558. n.file = filepath.Base(f)
  559. }
  560. if ln := sample.Info.Lineno; ln != 0 && n.line == 0 {
  561. n.line = ln
  562. }
  563. if f := sample.Info.Name; f != "" && n.function == "" {
  564. n.function = f
  565. }
  566. }
  567. asm = append(asm, n)
  568. }
  569. return asm
  570. }
  571. // valueOrDot formats a value according to a report, intercepting zero
  572. // values.
  573. func valueOrDot(value int64, rpt *Report) string {
  574. if value == 0 {
  575. return "."
  576. }
  577. return rpt.formatValue(value)
  578. }
  579. // printTags collects all tags referenced in the profile and prints
  580. // them in a sorted table.
  581. func printTags(w io.Writer, rpt *Report) error {
  582. p := rpt.prof
  583. o := rpt.options
  584. formatTag := func(v int64, key string) string {
  585. return measurement.ScaledLabel(v, key, o.OutputUnit)
  586. }
  587. // Hashtable to keep accumulate tags as key,value,count.
  588. tagMap := make(map[string]map[string]int64)
  589. for _, s := range p.Sample {
  590. for key, vals := range s.Label {
  591. for _, val := range vals {
  592. valueMap, ok := tagMap[key]
  593. if !ok {
  594. valueMap = make(map[string]int64)
  595. tagMap[key] = valueMap
  596. }
  597. valueMap[val] += o.SampleValue(s.Value)
  598. }
  599. }
  600. for key, vals := range s.NumLabel {
  601. unit := o.NumLabelUnits[key]
  602. for _, nval := range vals {
  603. val := formatTag(nval, unit)
  604. valueMap, ok := tagMap[key]
  605. if !ok {
  606. valueMap = make(map[string]int64)
  607. tagMap[key] = valueMap
  608. }
  609. valueMap[val] += o.SampleValue(s.Value)
  610. }
  611. }
  612. }
  613. tagKeys := make([]*graph.Tag, 0, len(tagMap))
  614. for key := range tagMap {
  615. tagKeys = append(tagKeys, &graph.Tag{Name: key})
  616. }
  617. tabw := tabwriter.NewWriter(w, 0, 0, 1, ' ', tabwriter.AlignRight)
  618. for _, tagKey := range graph.SortTags(tagKeys, true) {
  619. var total int64
  620. key := tagKey.Name
  621. tags := make([]*graph.Tag, 0, len(tagMap[key]))
  622. for t, c := range tagMap[key] {
  623. total += c
  624. tags = append(tags, &graph.Tag{Name: t, Flat: c})
  625. }
  626. f, u := measurement.Scale(total, o.SampleUnit, o.OutputUnit)
  627. fmt.Fprintf(tabw, "%s:\t Total %.1f%s\n", key, f, u)
  628. for _, t := range graph.SortTags(tags, true) {
  629. f, u := measurement.Scale(t.FlatValue(), o.SampleUnit, o.OutputUnit)
  630. if total > 0 {
  631. fmt.Fprintf(tabw, " \t%.1f%s (%s):\t %s\n", f, u, percentage(t.FlatValue(), total), t.Name)
  632. } else {
  633. fmt.Fprintf(tabw, " \t%.1f%s:\t %s\n", f, u, t.Name)
  634. }
  635. }
  636. fmt.Fprintln(tabw)
  637. }
  638. return tabw.Flush()
  639. }
  640. // printComments prints all freeform comments in the profile.
  641. func printComments(w io.Writer, rpt *Report) error {
  642. p := rpt.prof
  643. for _, c := range p.Comments {
  644. fmt.Fprintln(w, c)
  645. }
  646. return nil
  647. }
  648. // TextItem holds a single text report entry.
  649. type TextItem struct {
  650. Name string
  651. InlineLabel string // Not empty if inlined
  652. Flat, Cum int64 // Raw values
  653. FlatFormat, CumFormat string // Formatted values
  654. }
  655. // TextItems returns a list of text items from the report and a list
  656. // of labels that describe the report.
  657. func TextItems(rpt *Report) ([]TextItem, []string) {
  658. g, origCount, droppedNodes, _ := rpt.newTrimmedGraph()
  659. rpt.selectOutputUnit(g)
  660. labels := reportLabels(rpt, g, origCount, droppedNodes, 0, false)
  661. var items []TextItem
  662. var flatSum int64
  663. for _, n := range g.Nodes {
  664. name, flat, cum := n.Info.PrintableName(), n.FlatValue(), n.CumValue()
  665. var inline, noinline bool
  666. for _, e := range n.In {
  667. if e.Inline {
  668. inline = true
  669. } else {
  670. noinline = true
  671. }
  672. }
  673. var inl string
  674. if inline {
  675. if noinline {
  676. inl = "(partial-inline)"
  677. } else {
  678. inl = "(inline)"
  679. }
  680. }
  681. flatSum += flat
  682. items = append(items, TextItem{
  683. Name: name,
  684. InlineLabel: inl,
  685. Flat: flat,
  686. Cum: cum,
  687. FlatFormat: rpt.formatValue(flat),
  688. CumFormat: rpt.formatValue(cum),
  689. })
  690. }
  691. return items, labels
  692. }
  693. // printText prints a flat text report for a profile.
  694. func printText(w io.Writer, rpt *Report) error {
  695. items, labels := TextItems(rpt)
  696. fmt.Fprintln(w, strings.Join(labels, "\n"))
  697. fmt.Fprintf(w, "%10s %5s%% %5s%% %10s %5s%%\n",
  698. "flat", "flat", "sum", "cum", "cum")
  699. var flatSum int64
  700. for _, item := range items {
  701. inl := item.InlineLabel
  702. if inl != "" {
  703. inl = " " + inl
  704. }
  705. flatSum += item.Flat
  706. fmt.Fprintf(w, "%10s %s %s %10s %s %s%s\n",
  707. item.FlatFormat, percentage(item.Flat, rpt.total),
  708. percentage(flatSum, rpt.total),
  709. item.CumFormat, percentage(item.Cum, rpt.total),
  710. item.Name, inl)
  711. }
  712. return nil
  713. }
  714. // printTraces prints all traces from a profile.
  715. func printTraces(w io.Writer, rpt *Report) error {
  716. fmt.Fprintln(w, strings.Join(ProfileLabels(rpt), "\n"))
  717. prof := rpt.prof
  718. o := rpt.options
  719. const separator = "-----------+-------------------------------------------------------"
  720. _, locations := graph.CreateNodes(prof, &graph.Options{})
  721. for _, sample := range prof.Sample {
  722. var stack graph.Nodes
  723. for _, loc := range sample.Location {
  724. id := loc.ID
  725. stack = append(stack, locations[id]...)
  726. }
  727. if len(stack) == 0 {
  728. continue
  729. }
  730. fmt.Fprintln(w, separator)
  731. // Print any text labels for the sample.
  732. var labels []string
  733. for s, vs := range sample.Label {
  734. labels = append(labels, fmt.Sprintf("%10s: %s\n", s, strings.Join(vs, " ")))
  735. }
  736. sort.Strings(labels)
  737. fmt.Fprint(w, strings.Join(labels, ""))
  738. // Print any numeric labels for the sample
  739. var numLabels []string
  740. for key, vals := range sample.NumLabel {
  741. unit := o.NumLabelUnits[key]
  742. numValues := make([]string, len(vals))
  743. for i, vv := range vals {
  744. numValues[i] = measurement.Label(vv, unit)
  745. }
  746. numLabels = append(numLabels, fmt.Sprintf("%10s: %s\n", key, strings.Join(numValues, " ")))
  747. }
  748. sort.Strings(numLabels)
  749. fmt.Fprint(w, strings.Join(numLabels, ""))
  750. var d, v int64
  751. v = o.SampleValue(sample.Value)
  752. if o.SampleMeanDivisor != nil {
  753. d = o.SampleMeanDivisor(sample.Value)
  754. }
  755. // Print call stack.
  756. if d != 0 {
  757. v = v / d
  758. }
  759. fmt.Fprintf(w, "%10s %s\n",
  760. rpt.formatValue(v), stack[0].Info.PrintableName())
  761. for _, s := range stack[1:] {
  762. fmt.Fprintf(w, "%10s %s\n", "", s.Info.PrintableName())
  763. }
  764. }
  765. fmt.Fprintln(w, separator)
  766. return nil
  767. }
  768. // printCallgrind prints a graph for a profile on callgrind format.
  769. func printCallgrind(w io.Writer, rpt *Report) error {
  770. o := rpt.options
  771. rpt.options.NodeFraction = 0
  772. rpt.options.EdgeFraction = 0
  773. rpt.options.NodeCount = 0
  774. g, _, _, _ := rpt.newTrimmedGraph()
  775. rpt.selectOutputUnit(g)
  776. nodeNames := getDisambiguatedNames(g)
  777. fmt.Fprintln(w, "positions: instr line")
  778. fmt.Fprintln(w, "events:", o.SampleType+"("+o.OutputUnit+")")
  779. objfiles := make(map[string]int)
  780. files := make(map[string]int)
  781. names := make(map[string]int)
  782. // prevInfo points to the previous NodeInfo.
  783. // It is used to group cost lines together as much as possible.
  784. var prevInfo *graph.NodeInfo
  785. for _, n := range g.Nodes {
  786. if prevInfo == nil || n.Info.Objfile != prevInfo.Objfile || n.Info.File != prevInfo.File || n.Info.Name != prevInfo.Name {
  787. fmt.Fprintln(w)
  788. fmt.Fprintln(w, "ob="+callgrindName(objfiles, n.Info.Objfile))
  789. fmt.Fprintln(w, "fl="+callgrindName(files, n.Info.File))
  790. fmt.Fprintln(w, "fn="+callgrindName(names, n.Info.Name))
  791. }
  792. addr := callgrindAddress(prevInfo, n.Info.Address)
  793. sv, _ := measurement.Scale(n.FlatValue(), o.SampleUnit, o.OutputUnit)
  794. fmt.Fprintf(w, "%s %d %d\n", addr, n.Info.Lineno, int64(sv))
  795. // Print outgoing edges.
  796. for _, out := range n.Out.Sort() {
  797. c, _ := measurement.Scale(out.Weight, o.SampleUnit, o.OutputUnit)
  798. callee := out.Dest
  799. fmt.Fprintln(w, "cfl="+callgrindName(files, callee.Info.File))
  800. fmt.Fprintln(w, "cfn="+callgrindName(names, nodeNames[callee]))
  801. // pprof doesn't have a flat weight for a call, leave as 0.
  802. fmt.Fprintf(w, "calls=0 %s %d\n", callgrindAddress(prevInfo, callee.Info.Address), callee.Info.Lineno)
  803. // TODO: This address may be in the middle of a call
  804. // instruction. It would be best to find the beginning
  805. // of the instruction, but the tools seem to handle
  806. // this OK.
  807. fmt.Fprintf(w, "* * %d\n", int64(c))
  808. }
  809. prevInfo = &n.Info
  810. }
  811. return nil
  812. }
  813. // getDisambiguatedNames returns a map from each node in the graph to
  814. // the name to use in the callgrind output. Callgrind merges all
  815. // functions with the same [file name, function name]. Add a [%d/n]
  816. // suffix to disambiguate nodes with different values of
  817. // node.Function, which we want to keep separate. In particular, this
  818. // affects graphs created with --call_tree, where nodes from different
  819. // contexts are associated to different Functions.
  820. func getDisambiguatedNames(g *graph.Graph) map[*graph.Node]string {
  821. nodeName := make(map[*graph.Node]string, len(g.Nodes))
  822. type names struct {
  823. file, function string
  824. }
  825. // nameFunctionIndex maps the callgrind names (filename, function)
  826. // to the node.Function values found for that name, and each
  827. // node.Function value to a sequential index to be used on the
  828. // disambiguated name.
  829. nameFunctionIndex := make(map[names]map[*graph.Node]int)
  830. for _, n := range g.Nodes {
  831. nm := names{n.Info.File, n.Info.Name}
  832. p, ok := nameFunctionIndex[nm]
  833. if !ok {
  834. p = make(map[*graph.Node]int)
  835. nameFunctionIndex[nm] = p
  836. }
  837. if _, ok := p[n.Function]; !ok {
  838. p[n.Function] = len(p)
  839. }
  840. }
  841. for _, n := range g.Nodes {
  842. nm := names{n.Info.File, n.Info.Name}
  843. nodeName[n] = n.Info.Name
  844. if p := nameFunctionIndex[nm]; len(p) > 1 {
  845. // If there is more than one function, add suffix to disambiguate.
  846. nodeName[n] += fmt.Sprintf(" [%d/%d]", p[n.Function]+1, len(p))
  847. }
  848. }
  849. return nodeName
  850. }
  851. // callgrindName implements the callgrind naming compression scheme.
  852. // For names not previously seen returns "(N) name", where N is a
  853. // unique index. For names previously seen returns "(N)" where N is
  854. // the index returned the first time.
  855. func callgrindName(names map[string]int, name string) string {
  856. if name == "" {
  857. return ""
  858. }
  859. if id, ok := names[name]; ok {
  860. return fmt.Sprintf("(%d)", id)
  861. }
  862. id := len(names) + 1
  863. names[name] = id
  864. return fmt.Sprintf("(%d) %s", id, name)
  865. }
  866. // callgrindAddress implements the callgrind subposition compression scheme if
  867. // possible. If prevInfo != nil, it contains the previous address. The current
  868. // address can be given relative to the previous address, with an explicit +/-
  869. // to indicate it is relative, or * for the same address.
  870. func callgrindAddress(prevInfo *graph.NodeInfo, curr uint64) string {
  871. abs := fmt.Sprintf("%#x", curr)
  872. if prevInfo == nil {
  873. return abs
  874. }
  875. prev := prevInfo.Address
  876. if prev == curr {
  877. return "*"
  878. }
  879. diff := int64(curr - prev)
  880. relative := fmt.Sprintf("%+d", diff)
  881. // Only bother to use the relative address if it is actually shorter.
  882. if len(relative) < len(abs) {
  883. return relative
  884. }
  885. return abs
  886. }
  887. // printTree prints a tree-based report in text form.
  888. func printTree(w io.Writer, rpt *Report) error {
  889. const separator = "----------------------------------------------------------+-------------"
  890. const legend = " flat flat% sum% cum cum% calls calls% + context "
  891. g, origCount, droppedNodes, _ := rpt.newTrimmedGraph()
  892. rpt.selectOutputUnit(g)
  893. fmt.Fprintln(w, strings.Join(reportLabels(rpt, g, origCount, droppedNodes, 0, false), "\n"))
  894. fmt.Fprintln(w, separator)
  895. fmt.Fprintln(w, legend)
  896. var flatSum int64
  897. rx := rpt.options.Symbol
  898. for _, n := range g.Nodes {
  899. name, flat, cum := n.Info.PrintableName(), n.FlatValue(), n.CumValue()
  900. // Skip any entries that do not match the regexp (for the "peek" command).
  901. if rx != nil && !rx.MatchString(name) {
  902. continue
  903. }
  904. fmt.Fprintln(w, separator)
  905. // Print incoming edges.
  906. inEdges := n.In.Sort()
  907. for _, in := range inEdges {
  908. var inline string
  909. if in.Inline {
  910. inline = " (inline)"
  911. }
  912. fmt.Fprintf(w, "%50s %s | %s%s\n", rpt.formatValue(in.Weight),
  913. percentage(in.Weight, cum), in.Src.Info.PrintableName(), inline)
  914. }
  915. // Print current node.
  916. flatSum += flat
  917. fmt.Fprintf(w, "%10s %s %s %10s %s | %s\n",
  918. rpt.formatValue(flat),
  919. percentage(flat, rpt.total),
  920. percentage(flatSum, rpt.total),
  921. rpt.formatValue(cum),
  922. percentage(cum, rpt.total),
  923. name)
  924. // Print outgoing edges.
  925. outEdges := n.Out.Sort()
  926. for _, out := range outEdges {
  927. var inline string
  928. if out.Inline {
  929. inline = " (inline)"
  930. }
  931. fmt.Fprintf(w, "%50s %s | %s%s\n", rpt.formatValue(out.Weight),
  932. percentage(out.Weight, cum), out.Dest.Info.PrintableName(), inline)
  933. }
  934. }
  935. if len(g.Nodes) > 0 {
  936. fmt.Fprintln(w, separator)
  937. }
  938. return nil
  939. }
  940. // GetDOT returns a graph suitable for dot processing along with some
  941. // configuration information.
  942. func GetDOT(rpt *Report) (*graph.Graph, *graph.DotConfig) {
  943. g, origCount, droppedNodes, droppedEdges := rpt.newTrimmedGraph()
  944. rpt.selectOutputUnit(g)
  945. labels := reportLabels(rpt, g, origCount, droppedNodes, droppedEdges, true)
  946. c := &graph.DotConfig{
  947. Title: rpt.options.Title,
  948. Labels: labels,
  949. FormatValue: rpt.formatValue,
  950. Total: rpt.total,
  951. }
  952. return g, c
  953. }
  954. // printDOT prints an annotated callgraph in DOT format.
  955. func printDOT(w io.Writer, rpt *Report) error {
  956. g, c := GetDOT(rpt)
  957. graph.ComposeDot(w, g, &graph.DotAttributes{}, c)
  958. return nil
  959. }
  960. // percentage computes the percentage of total of a value, and encodes
  961. // it as a string. At least two digits of precision are printed.
  962. func percentage(value, total int64) string {
  963. var ratio float64
  964. if total != 0 {
  965. ratio = math.Abs(float64(value)/float64(total)) * 100
  966. }
  967. switch {
  968. case math.Abs(ratio) >= 99.95 && math.Abs(ratio) <= 100.05:
  969. return " 100%"
  970. case math.Abs(ratio) >= 1.0:
  971. return fmt.Sprintf("%5.2f%%", ratio)
  972. default:
  973. return fmt.Sprintf("%5.2g%%", ratio)
  974. }
  975. }
  976. // ProfileLabels returns printable labels for a profile.
  977. func ProfileLabels(rpt *Report) []string {
  978. label := []string{}
  979. prof := rpt.prof
  980. o := rpt.options
  981. if len(prof.Mapping) > 0 {
  982. if prof.Mapping[0].File != "" {
  983. label = append(label, "File: "+filepath.Base(prof.Mapping[0].File))
  984. }
  985. if prof.Mapping[0].BuildID != "" {
  986. label = append(label, "Build ID: "+prof.Mapping[0].BuildID)
  987. }
  988. }
  989. // Only include comments that do not start with '#'.
  990. for _, c := range prof.Comments {
  991. if !strings.HasPrefix(c, "#") {
  992. label = append(label, c)
  993. }
  994. }
  995. if o.SampleType != "" {
  996. label = append(label, "Type: "+o.SampleType)
  997. }
  998. if prof.TimeNanos != 0 {
  999. const layout = "Jan 2, 2006 at 3:04pm (MST)"
  1000. label = append(label, "Time: "+time.Unix(0, prof.TimeNanos).Format(layout))
  1001. }
  1002. if prof.DurationNanos != 0 {
  1003. duration := measurement.Label(prof.DurationNanos, "nanoseconds")
  1004. totalNanos, totalUnit := measurement.Scale(rpt.total, o.SampleUnit, "nanoseconds")
  1005. var ratio string
  1006. if totalUnit == "ns" && totalNanos != 0 {
  1007. ratio = "(" + percentage(int64(totalNanos), prof.DurationNanos) + ")"
  1008. }
  1009. label = append(label, fmt.Sprintf("Duration: %s, Total samples = %s %s", duration, rpt.formatValue(rpt.total), ratio))
  1010. }
  1011. return label
  1012. }
  1013. // reportLabels returns printable labels for a report. Includes
  1014. // profileLabels.
  1015. func reportLabels(rpt *Report, g *graph.Graph, origCount, droppedNodes, droppedEdges int, fullHeaders bool) []string {
  1016. nodeFraction := rpt.options.NodeFraction
  1017. edgeFraction := rpt.options.EdgeFraction
  1018. nodeCount := len(g.Nodes)
  1019. var label []string
  1020. if len(rpt.options.ProfileLabels) > 0 {
  1021. label = append(label, rpt.options.ProfileLabels...)
  1022. } else if fullHeaders || !rpt.options.CompactLabels {
  1023. label = ProfileLabels(rpt)
  1024. }
  1025. var flatSum int64
  1026. for _, n := range g.Nodes {
  1027. flatSum = flatSum + n.FlatValue()
  1028. }
  1029. if len(rpt.options.ActiveFilters) > 0 {
  1030. activeFilters := legendActiveFilters(rpt.options.ActiveFilters)
  1031. label = append(label, activeFilters...)
  1032. }
  1033. 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)))
  1034. if rpt.total != 0 {
  1035. if droppedNodes > 0 {
  1036. label = append(label, genLabel(droppedNodes, "node", "cum",
  1037. rpt.formatValue(abs64(int64(float64(rpt.total)*nodeFraction)))))
  1038. }
  1039. if droppedEdges > 0 {
  1040. label = append(label, genLabel(droppedEdges, "edge", "freq",
  1041. rpt.formatValue(abs64(int64(float64(rpt.total)*edgeFraction)))))
  1042. }
  1043. if nodeCount > 0 && nodeCount < origCount {
  1044. label = append(label, fmt.Sprintf("Showing top %d nodes out of %d",
  1045. nodeCount, origCount))
  1046. }
  1047. }
  1048. return label
  1049. }
  1050. func legendActiveFilters(activeFilters []string) []string {
  1051. legendActiveFilters := make([]string, len(activeFilters)+1)
  1052. legendActiveFilters[0] = "Active filters:"
  1053. for i, s := range activeFilters {
  1054. if len(s) > 80 {
  1055. s = s[:80] + "…"
  1056. }
  1057. legendActiveFilters[i+1] = " " + s
  1058. }
  1059. return legendActiveFilters
  1060. }
  1061. func genLabel(d int, n, l, f string) string {
  1062. if d > 1 {
  1063. n = n + "s"
  1064. }
  1065. return fmt.Sprintf("Dropped %d %s (%s <= %s)", d, n, l, f)
  1066. }
  1067. // New builds a new report indexing the sample values interpreting the
  1068. // samples with the provided function.
  1069. func New(prof *profile.Profile, o *Options) *Report {
  1070. format := func(v int64) string {
  1071. if r := o.Ratio; r > 0 && r != 1 {
  1072. fv := float64(v) * r
  1073. v = int64(fv)
  1074. }
  1075. return measurement.ScaledLabel(v, o.SampleUnit, o.OutputUnit)
  1076. }
  1077. return &Report{prof, computeTotal(prof, o.SampleValue, o.SampleMeanDivisor, !o.PositivePercentages),
  1078. o, format}
  1079. }
  1080. // NewDefault builds a new report indexing the last sample value
  1081. // available.
  1082. func NewDefault(prof *profile.Profile, options Options) *Report {
  1083. index := len(prof.SampleType) - 1
  1084. o := &options
  1085. if o.Title == "" && len(prof.Mapping) > 0 && prof.Mapping[0].File != "" {
  1086. o.Title = filepath.Base(prof.Mapping[0].File)
  1087. }
  1088. o.SampleType = prof.SampleType[index].Type
  1089. o.SampleUnit = strings.ToLower(prof.SampleType[index].Unit)
  1090. o.SampleValue = func(v []int64) int64 {
  1091. return v[index]
  1092. }
  1093. return New(prof, o)
  1094. }
  1095. // computeTotal computes the sum of all sample values. This will be
  1096. // used to compute percentages. If includeNegative is set, use use
  1097. // absolute values to provide a meaningful percentage for both
  1098. // negative and positive values. Otherwise only use positive values,
  1099. // which is useful when comparing profiles from different jobs.
  1100. func computeTotal(prof *profile.Profile, value, meanDiv func(v []int64) int64, includeNegative bool) int64 {
  1101. var div, ret int64
  1102. for _, sample := range prof.Sample {
  1103. var d, v int64
  1104. v = value(sample.Value)
  1105. if meanDiv != nil {
  1106. d = meanDiv(sample.Value)
  1107. }
  1108. if v >= 0 {
  1109. ret += v
  1110. div += d
  1111. } else if includeNegative {
  1112. ret -= v
  1113. div += d
  1114. }
  1115. }
  1116. if div != 0 {
  1117. return ret / div
  1118. }
  1119. return ret
  1120. }
  1121. // Report contains the data and associated routines to extract a
  1122. // report from a profile.
  1123. type Report struct {
  1124. prof *profile.Profile
  1125. total int64
  1126. options *Options
  1127. formatValue func(int64) string
  1128. }
  1129. // Total returns the total number of samples in a report.
  1130. func (rpt *Report) Total() int64 { return rpt.total }
  1131. func abs64(i int64) int64 {
  1132. if i < 0 {
  1133. return -i
  1134. }
  1135. return i
  1136. }