설명 없음

report.go 36KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304
  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. type stk struct {
  746. *graph.NodeInfo
  747. inline bool
  748. }
  749. var stack []stk
  750. for _, loc := range sample.Location {
  751. nodes := locations[loc.ID]
  752. for i, n := range nodes {
  753. // The inline flag may be inaccurate if 'show' or 'hide' filter is
  754. // used. See https://github.com/google/pprof/issues/511.
  755. inline := i != len(nodes)-1
  756. stack = append(stack, stk{&n.Info, inline})
  757. }
  758. }
  759. if len(stack) == 0 {
  760. continue
  761. }
  762. fmt.Fprintln(w, separator)
  763. // Print any text labels for the sample.
  764. var labels []string
  765. for s, vs := range sample.Label {
  766. labels = append(labels, fmt.Sprintf("%10s: %s\n", s, strings.Join(vs, " ")))
  767. }
  768. sort.Strings(labels)
  769. fmt.Fprint(w, strings.Join(labels, ""))
  770. // Print any numeric labels for the sample
  771. var numLabels []string
  772. for key, vals := range sample.NumLabel {
  773. unit := o.NumLabelUnits[key]
  774. numValues := make([]string, len(vals))
  775. for i, vv := range vals {
  776. numValues[i] = measurement.Label(vv, unit)
  777. }
  778. numLabels = append(numLabels, fmt.Sprintf("%10s: %s\n", key, strings.Join(numValues, " ")))
  779. }
  780. sort.Strings(numLabels)
  781. fmt.Fprint(w, strings.Join(numLabels, ""))
  782. var d, v int64
  783. v = o.SampleValue(sample.Value)
  784. if o.SampleMeanDivisor != nil {
  785. d = o.SampleMeanDivisor(sample.Value)
  786. }
  787. // Print call stack.
  788. if d != 0 {
  789. v = v / d
  790. }
  791. for i, s := range stack {
  792. var vs, inline string
  793. if i == 0 {
  794. vs = rpt.formatValue(v)
  795. }
  796. if s.inline {
  797. inline = " (inline)"
  798. }
  799. fmt.Fprintf(w, "%10s %s%s\n", vs, s.PrintableName(), inline)
  800. }
  801. }
  802. fmt.Fprintln(w, separator)
  803. return nil
  804. }
  805. // printCallgrind prints a graph for a profile on callgrind format.
  806. func printCallgrind(w io.Writer, rpt *Report) error {
  807. o := rpt.options
  808. rpt.options.NodeFraction = 0
  809. rpt.options.EdgeFraction = 0
  810. rpt.options.NodeCount = 0
  811. g, _, _, _ := rpt.newTrimmedGraph()
  812. rpt.selectOutputUnit(g)
  813. nodeNames := getDisambiguatedNames(g)
  814. fmt.Fprintln(w, "positions: instr line")
  815. fmt.Fprintln(w, "events:", o.SampleType+"("+o.OutputUnit+")")
  816. objfiles := make(map[string]int)
  817. files := make(map[string]int)
  818. names := make(map[string]int)
  819. // prevInfo points to the previous NodeInfo.
  820. // It is used to group cost lines together as much as possible.
  821. var prevInfo *graph.NodeInfo
  822. for _, n := range g.Nodes {
  823. if prevInfo == nil || n.Info.Objfile != prevInfo.Objfile || n.Info.File != prevInfo.File || n.Info.Name != prevInfo.Name {
  824. fmt.Fprintln(w)
  825. fmt.Fprintln(w, "ob="+callgrindName(objfiles, n.Info.Objfile))
  826. fmt.Fprintln(w, "fl="+callgrindName(files, n.Info.File))
  827. fmt.Fprintln(w, "fn="+callgrindName(names, n.Info.Name))
  828. }
  829. addr := callgrindAddress(prevInfo, n.Info.Address)
  830. sv, _ := measurement.Scale(n.FlatValue(), o.SampleUnit, o.OutputUnit)
  831. fmt.Fprintf(w, "%s %d %d\n", addr, n.Info.Lineno, int64(sv))
  832. // Print outgoing edges.
  833. for _, out := range n.Out.Sort() {
  834. c, _ := measurement.Scale(out.Weight, o.SampleUnit, o.OutputUnit)
  835. callee := out.Dest
  836. fmt.Fprintln(w, "cfl="+callgrindName(files, callee.Info.File))
  837. fmt.Fprintln(w, "cfn="+callgrindName(names, nodeNames[callee]))
  838. // pprof doesn't have a flat weight for a call, leave as 0.
  839. fmt.Fprintf(w, "calls=0 %s %d\n", callgrindAddress(prevInfo, callee.Info.Address), callee.Info.Lineno)
  840. // TODO: This address may be in the middle of a call
  841. // instruction. It would be best to find the beginning
  842. // of the instruction, but the tools seem to handle
  843. // this OK.
  844. fmt.Fprintf(w, "* * %d\n", int64(c))
  845. }
  846. prevInfo = &n.Info
  847. }
  848. return nil
  849. }
  850. // getDisambiguatedNames returns a map from each node in the graph to
  851. // the name to use in the callgrind output. Callgrind merges all
  852. // functions with the same [file name, function name]. Add a [%d/n]
  853. // suffix to disambiguate nodes with different values of
  854. // node.Function, which we want to keep separate. In particular, this
  855. // affects graphs created with --call_tree, where nodes from different
  856. // contexts are associated to different Functions.
  857. func getDisambiguatedNames(g *graph.Graph) map[*graph.Node]string {
  858. nodeName := make(map[*graph.Node]string, len(g.Nodes))
  859. type names struct {
  860. file, function string
  861. }
  862. // nameFunctionIndex maps the callgrind names (filename, function)
  863. // to the node.Function values found for that name, and each
  864. // node.Function value to a sequential index to be used on the
  865. // disambiguated name.
  866. nameFunctionIndex := make(map[names]map[*graph.Node]int)
  867. for _, n := range g.Nodes {
  868. nm := names{n.Info.File, n.Info.Name}
  869. p, ok := nameFunctionIndex[nm]
  870. if !ok {
  871. p = make(map[*graph.Node]int)
  872. nameFunctionIndex[nm] = p
  873. }
  874. if _, ok := p[n.Function]; !ok {
  875. p[n.Function] = len(p)
  876. }
  877. }
  878. for _, n := range g.Nodes {
  879. nm := names{n.Info.File, n.Info.Name}
  880. nodeName[n] = n.Info.Name
  881. if p := nameFunctionIndex[nm]; len(p) > 1 {
  882. // If there is more than one function, add suffix to disambiguate.
  883. nodeName[n] += fmt.Sprintf(" [%d/%d]", p[n.Function]+1, len(p))
  884. }
  885. }
  886. return nodeName
  887. }
  888. // callgrindName implements the callgrind naming compression scheme.
  889. // For names not previously seen returns "(N) name", where N is a
  890. // unique index. For names previously seen returns "(N)" where N is
  891. // the index returned the first time.
  892. func callgrindName(names map[string]int, name string) string {
  893. if name == "" {
  894. return ""
  895. }
  896. if id, ok := names[name]; ok {
  897. return fmt.Sprintf("(%d)", id)
  898. }
  899. id := len(names) + 1
  900. names[name] = id
  901. return fmt.Sprintf("(%d) %s", id, name)
  902. }
  903. // callgrindAddress implements the callgrind subposition compression scheme if
  904. // possible. If prevInfo != nil, it contains the previous address. The current
  905. // address can be given relative to the previous address, with an explicit +/-
  906. // to indicate it is relative, or * for the same address.
  907. func callgrindAddress(prevInfo *graph.NodeInfo, curr uint64) string {
  908. abs := fmt.Sprintf("%#x", curr)
  909. if prevInfo == nil {
  910. return abs
  911. }
  912. prev := prevInfo.Address
  913. if prev == curr {
  914. return "*"
  915. }
  916. diff := int64(curr - prev)
  917. relative := fmt.Sprintf("%+d", diff)
  918. // Only bother to use the relative address if it is actually shorter.
  919. if len(relative) < len(abs) {
  920. return relative
  921. }
  922. return abs
  923. }
  924. // printTree prints a tree-based report in text form.
  925. func printTree(w io.Writer, rpt *Report) error {
  926. const separator = "----------------------------------------------------------+-------------"
  927. const legend = " flat flat% sum% cum cum% calls calls% + context "
  928. g, origCount, droppedNodes, _ := rpt.newTrimmedGraph()
  929. rpt.selectOutputUnit(g)
  930. fmt.Fprintln(w, strings.Join(reportLabels(rpt, g, origCount, droppedNodes, 0, false), "\n"))
  931. fmt.Fprintln(w, separator)
  932. fmt.Fprintln(w, legend)
  933. var flatSum int64
  934. rx := rpt.options.Symbol
  935. for _, n := range g.Nodes {
  936. name, flat, cum := n.Info.PrintableName(), n.FlatValue(), n.CumValue()
  937. // Skip any entries that do not match the regexp (for the "peek" command).
  938. if rx != nil && !rx.MatchString(name) {
  939. continue
  940. }
  941. fmt.Fprintln(w, separator)
  942. // Print incoming edges.
  943. inEdges := n.In.Sort()
  944. for _, in := range inEdges {
  945. var inline string
  946. if in.Inline {
  947. inline = " (inline)"
  948. }
  949. fmt.Fprintf(w, "%50s %s | %s%s\n", rpt.formatValue(in.Weight),
  950. measurement.Percentage(in.Weight, cum), in.Src.Info.PrintableName(), inline)
  951. }
  952. // Print current node.
  953. flatSum += flat
  954. fmt.Fprintf(w, "%10s %s %s %10s %s | %s\n",
  955. rpt.formatValue(flat),
  956. measurement.Percentage(flat, rpt.total),
  957. measurement.Percentage(flatSum, rpt.total),
  958. rpt.formatValue(cum),
  959. measurement.Percentage(cum, rpt.total),
  960. name)
  961. // Print outgoing edges.
  962. outEdges := n.Out.Sort()
  963. for _, out := range outEdges {
  964. var inline string
  965. if out.Inline {
  966. inline = " (inline)"
  967. }
  968. fmt.Fprintf(w, "%50s %s | %s%s\n", rpt.formatValue(out.Weight),
  969. measurement.Percentage(out.Weight, cum), out.Dest.Info.PrintableName(), inline)
  970. }
  971. }
  972. if len(g.Nodes) > 0 {
  973. fmt.Fprintln(w, separator)
  974. }
  975. return nil
  976. }
  977. // GetDOT returns a graph suitable for dot processing along with some
  978. // configuration information.
  979. func GetDOT(rpt *Report) (*graph.Graph, *graph.DotConfig) {
  980. g, origCount, droppedNodes, droppedEdges := rpt.newTrimmedGraph()
  981. rpt.selectOutputUnit(g)
  982. labels := reportLabels(rpt, g, origCount, droppedNodes, droppedEdges, true)
  983. c := &graph.DotConfig{
  984. Title: rpt.options.Title,
  985. Labels: labels,
  986. FormatValue: rpt.formatValue,
  987. Total: rpt.total,
  988. }
  989. return g, c
  990. }
  991. // printDOT prints an annotated callgraph in DOT format.
  992. func printDOT(w io.Writer, rpt *Report) error {
  993. g, c := GetDOT(rpt)
  994. graph.ComposeDot(w, g, &graph.DotAttributes{}, c)
  995. return nil
  996. }
  997. // ProfileLabels returns printable labels for a profile.
  998. func ProfileLabels(rpt *Report) []string {
  999. label := []string{}
  1000. prof := rpt.prof
  1001. o := rpt.options
  1002. if len(prof.Mapping) > 0 {
  1003. if prof.Mapping[0].File != "" {
  1004. label = append(label, "File: "+filepath.Base(prof.Mapping[0].File))
  1005. }
  1006. if prof.Mapping[0].BuildID != "" {
  1007. label = append(label, "Build ID: "+prof.Mapping[0].BuildID)
  1008. }
  1009. }
  1010. // Only include comments that do not start with '#'.
  1011. for _, c := range prof.Comments {
  1012. if !strings.HasPrefix(c, "#") {
  1013. label = append(label, c)
  1014. }
  1015. }
  1016. if o.SampleType != "" {
  1017. label = append(label, "Type: "+o.SampleType)
  1018. }
  1019. if prof.TimeNanos != 0 {
  1020. const layout = "Jan 2, 2006 at 3:04pm (MST)"
  1021. label = append(label, "Time: "+time.Unix(0, prof.TimeNanos).Format(layout))
  1022. }
  1023. if prof.DurationNanos != 0 {
  1024. duration := measurement.Label(prof.DurationNanos, "nanoseconds")
  1025. totalNanos, totalUnit := measurement.Scale(rpt.total, o.SampleUnit, "nanoseconds")
  1026. var ratio string
  1027. if totalUnit == "ns" && totalNanos != 0 {
  1028. ratio = "(" + measurement.Percentage(int64(totalNanos), prof.DurationNanos) + ")"
  1029. }
  1030. label = append(label, fmt.Sprintf("Duration: %s, Total samples = %s %s", duration, rpt.formatValue(rpt.total), ratio))
  1031. }
  1032. return label
  1033. }
  1034. // reportLabels returns printable labels for a report. Includes
  1035. // profileLabels.
  1036. func reportLabels(rpt *Report, g *graph.Graph, origCount, droppedNodes, droppedEdges int, fullHeaders bool) []string {
  1037. nodeFraction := rpt.options.NodeFraction
  1038. edgeFraction := rpt.options.EdgeFraction
  1039. nodeCount := len(g.Nodes)
  1040. var label []string
  1041. if len(rpt.options.ProfileLabels) > 0 {
  1042. label = append(label, rpt.options.ProfileLabels...)
  1043. } else if fullHeaders || !rpt.options.CompactLabels {
  1044. label = ProfileLabels(rpt)
  1045. }
  1046. var flatSum int64
  1047. for _, n := range g.Nodes {
  1048. flatSum = flatSum + n.FlatValue()
  1049. }
  1050. if len(rpt.options.ActiveFilters) > 0 {
  1051. activeFilters := legendActiveFilters(rpt.options.ActiveFilters)
  1052. label = append(label, activeFilters...)
  1053. }
  1054. 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)))
  1055. if rpt.total != 0 {
  1056. if droppedNodes > 0 {
  1057. label = append(label, genLabel(droppedNodes, "node", "cum",
  1058. rpt.formatValue(abs64(int64(float64(rpt.total)*nodeFraction)))))
  1059. }
  1060. if droppedEdges > 0 {
  1061. label = append(label, genLabel(droppedEdges, "edge", "freq",
  1062. rpt.formatValue(abs64(int64(float64(rpt.total)*edgeFraction)))))
  1063. }
  1064. if nodeCount > 0 && nodeCount < origCount {
  1065. label = append(label, fmt.Sprintf("Showing top %d nodes out of %d",
  1066. nodeCount, origCount))
  1067. }
  1068. }
  1069. return label
  1070. }
  1071. func legendActiveFilters(activeFilters []string) []string {
  1072. legendActiveFilters := make([]string, len(activeFilters)+1)
  1073. legendActiveFilters[0] = "Active filters:"
  1074. for i, s := range activeFilters {
  1075. if len(s) > 80 {
  1076. s = s[:80] + "…"
  1077. }
  1078. legendActiveFilters[i+1] = " " + s
  1079. }
  1080. return legendActiveFilters
  1081. }
  1082. func genLabel(d int, n, l, f string) string {
  1083. if d > 1 {
  1084. n = n + "s"
  1085. }
  1086. return fmt.Sprintf("Dropped %d %s (%s <= %s)", d, n, l, f)
  1087. }
  1088. // New builds a new report indexing the sample values interpreting the
  1089. // samples with the provided function.
  1090. func New(prof *profile.Profile, o *Options) *Report {
  1091. format := func(v int64) string {
  1092. if r := o.Ratio; r > 0 && r != 1 {
  1093. fv := float64(v) * r
  1094. v = int64(fv)
  1095. }
  1096. return measurement.ScaledLabel(v, o.SampleUnit, o.OutputUnit)
  1097. }
  1098. return &Report{prof, computeTotal(prof, o.SampleValue, o.SampleMeanDivisor),
  1099. o, format}
  1100. }
  1101. // NewDefault builds a new report indexing the last sample value
  1102. // available.
  1103. func NewDefault(prof *profile.Profile, options Options) *Report {
  1104. index := len(prof.SampleType) - 1
  1105. o := &options
  1106. if o.Title == "" && len(prof.Mapping) > 0 && prof.Mapping[0].File != "" {
  1107. o.Title = filepath.Base(prof.Mapping[0].File)
  1108. }
  1109. o.SampleType = prof.SampleType[index].Type
  1110. o.SampleUnit = strings.ToLower(prof.SampleType[index].Unit)
  1111. o.SampleValue = func(v []int64) int64 {
  1112. return v[index]
  1113. }
  1114. return New(prof, o)
  1115. }
  1116. // computeTotal computes the sum of the absolute value of all sample values.
  1117. // If any samples have label indicating they belong to the diff base, then the
  1118. // total will only include samples with that label.
  1119. func computeTotal(prof *profile.Profile, value, meanDiv func(v []int64) int64) int64 {
  1120. var div, total, diffDiv, diffTotal int64
  1121. for _, sample := range prof.Sample {
  1122. var d, v int64
  1123. v = value(sample.Value)
  1124. if meanDiv != nil {
  1125. d = meanDiv(sample.Value)
  1126. }
  1127. if v < 0 {
  1128. v = -v
  1129. }
  1130. total += v
  1131. div += d
  1132. if sample.DiffBaseSample() {
  1133. diffTotal += v
  1134. diffDiv += d
  1135. }
  1136. }
  1137. if diffTotal > 0 {
  1138. total = diffTotal
  1139. div = diffDiv
  1140. }
  1141. if div != 0 {
  1142. return total / div
  1143. }
  1144. return total
  1145. }
  1146. // Report contains the data and associated routines to extract a
  1147. // report from a profile.
  1148. type Report struct {
  1149. prof *profile.Profile
  1150. total int64
  1151. options *Options
  1152. formatValue func(int64) string
  1153. }
  1154. // Total returns the total number of samples in a report.
  1155. func (rpt *Report) Total() int64 { return rpt.total }
  1156. func abs64(i int64) int64 {
  1157. if i < 0 {
  1158. return -i
  1159. }
  1160. return i
  1161. }