Без опису

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947
  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. "os"
  22. "path/filepath"
  23. "regexp"
  24. "sort"
  25. "strconv"
  26. "strings"
  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. // Generate generates a report as directed by the Report.
  34. func Generate(w io.Writer, rpt *Report, obj plugin.ObjTool) error {
  35. o := rpt.options
  36. switch o.OutputFormat {
  37. case Dot:
  38. return printDOT(w, rpt)
  39. case Tree:
  40. return printTree(w, rpt)
  41. case Text:
  42. return printText(w, rpt)
  43. case Traces:
  44. return printTraces(w, rpt)
  45. case Raw:
  46. fmt.Fprint(w, rpt.prof.String())
  47. return nil
  48. case Tags:
  49. return printTags(w, rpt)
  50. case Proto:
  51. return rpt.prof.Write(w)
  52. case TopProto:
  53. return printTopProto(w, rpt)
  54. case Dis:
  55. return printAssembly(w, rpt, obj)
  56. case List:
  57. return printSource(w, rpt)
  58. case WebList:
  59. return printWebSource(w, rpt, obj)
  60. case Callgrind:
  61. return printCallgrind(w, rpt)
  62. }
  63. return fmt.Errorf("unexpected output format")
  64. }
  65. // newTrimmedGraph creates a graph for this report, trimmed according
  66. // to the report options.
  67. func (rpt *Report) newTrimmedGraph() (g *graph.Graph, origCount, droppedNodes, droppedEdges int) {
  68. o := rpt.options
  69. // Build a graph and refine it. On each refinement step we must rebuild the graph from the samples,
  70. // as the graph itself doesn't contain enough information to preserve full precision.
  71. // First step: Build complete graph to identify low frequency nodes, based on their cum weight.
  72. g = rpt.newGraph(nil)
  73. totalValue, _ := g.Nodes.Sum()
  74. nodeCutoff := abs64(int64(float64(totalValue) * o.NodeFraction))
  75. edgeCutoff := abs64(int64(float64(totalValue) * o.EdgeFraction))
  76. // Filter out nodes with cum value below nodeCutoff.
  77. if nodeCutoff > 0 {
  78. if nodesKept := g.DiscardLowFrequencyNodes(nodeCutoff); len(g.Nodes) != len(nodesKept) {
  79. droppedNodes = len(g.Nodes) - len(nodesKept)
  80. g = rpt.newGraph(nodesKept)
  81. }
  82. }
  83. origCount = len(g.Nodes)
  84. // Second step: Limit the total number of nodes. Apply specialized heuristics to improve
  85. // visualization when generating dot output.
  86. visualMode := o.OutputFormat == Dot
  87. g.SortNodes(o.CumSort, visualMode)
  88. if nodeCount := o.NodeCount; nodeCount > 0 {
  89. // Remove low frequency tags and edges as they affect selection.
  90. g.TrimLowFrequencyTags(nodeCutoff)
  91. g.TrimLowFrequencyEdges(edgeCutoff)
  92. if nodesKept := g.SelectTopNodes(nodeCount, visualMode); len(nodesKept) != len(g.Nodes) {
  93. g = rpt.newGraph(nodesKept)
  94. g.SortNodes(o.CumSort, visualMode)
  95. }
  96. }
  97. // Final step: Filter out low frequency tags and edges, and remove redundant edges that clutter
  98. // the graph.
  99. g.TrimLowFrequencyTags(nodeCutoff)
  100. droppedEdges = g.TrimLowFrequencyEdges(edgeCutoff)
  101. if visualMode {
  102. g.RemoveRedundantEdges()
  103. }
  104. return
  105. }
  106. func (rpt *Report) selectOutputUnit(g *graph.Graph) {
  107. o := rpt.options
  108. // Select best unit for profile output.
  109. // Find the appropriate units for the smallest non-zero sample
  110. if o.OutputUnit != "minimum" || len(g.Nodes) == 0 {
  111. return
  112. }
  113. var minValue int64
  114. for _, n := range g.Nodes {
  115. nodeMin := abs64(n.Flat)
  116. if nodeMin == 0 {
  117. nodeMin = abs64(n.Cum)
  118. }
  119. if nodeMin > 0 && (minValue == 0 || nodeMin < minValue) {
  120. minValue = nodeMin
  121. }
  122. }
  123. maxValue := rpt.total
  124. if minValue == 0 {
  125. minValue = maxValue
  126. }
  127. if r := o.Ratio; r > 0 && r != 1 {
  128. minValue = int64(float64(minValue) * r)
  129. maxValue = int64(float64(maxValue) * r)
  130. }
  131. _, minUnit := measurement.Scale(minValue, o.SampleUnit, "minimum")
  132. _, maxUnit := measurement.Scale(maxValue, o.SampleUnit, "minimum")
  133. unit := minUnit
  134. if minUnit != maxUnit && minValue*100 < maxValue && o.OutputFormat != Callgrind {
  135. // Minimum and maximum values have different units. Scale
  136. // minimum by 100 to use larger units, allowing minimum value to
  137. // be scaled down to 0.01, except for callgrind reports since
  138. // they can only represent integer values.
  139. _, unit = measurement.Scale(100*minValue, o.SampleUnit, "minimum")
  140. }
  141. if unit != "" {
  142. o.OutputUnit = unit
  143. } else {
  144. o.OutputUnit = o.SampleUnit
  145. }
  146. }
  147. // newGraph creates a new graph for this report. If nodes is non-nil,
  148. // only nodes whose info matches are included. Otherwise, all nodes
  149. // are included, without trimming.
  150. func (rpt *Report) newGraph(nodes graph.NodeSet) *graph.Graph {
  151. o := rpt.options
  152. // Clean up file paths using heuristics.
  153. prof := rpt.prof
  154. for _, f := range prof.Function {
  155. f.Filename = trimPath(f.Filename)
  156. }
  157. gopt := &graph.Options{
  158. SampleValue: o.SampleValue,
  159. FormatTag: formatTag,
  160. CallTree: o.CallTree && o.OutputFormat == Dot,
  161. DropNegative: o.DropNegative,
  162. KeptNodes: nodes,
  163. }
  164. // Only keep binary names for disassembly-based reports, otherwise
  165. // remove it to allow merging of functions across binaries.
  166. switch o.OutputFormat {
  167. case Raw, List, WebList, Dis:
  168. gopt.ObjNames = true
  169. }
  170. return graph.New(rpt.prof, gopt)
  171. }
  172. func formatTag(v int64, key string) string {
  173. return measurement.Label(v, key)
  174. }
  175. func printTopProto(w io.Writer, rpt *Report) error {
  176. p := rpt.prof
  177. o := rpt.options
  178. g, _, _, _ := rpt.newTrimmedGraph()
  179. rpt.selectOutputUnit(g)
  180. out := profile.Profile{
  181. SampleType: []*profile.ValueType{
  182. {Type: "cum", Unit: o.OutputUnit},
  183. {Type: "flat", Unit: o.OutputUnit},
  184. },
  185. TimeNanos: p.TimeNanos,
  186. DurationNanos: p.DurationNanos,
  187. PeriodType: p.PeriodType,
  188. Period: p.Period,
  189. }
  190. var flatSum int64
  191. for i, n := range g.Nodes {
  192. name, flat, cum := n.Info.PrintableName(), n.Flat, n.Cum
  193. flatSum += flat
  194. f := &profile.Function{
  195. ID: uint64(i + 1),
  196. Name: name,
  197. SystemName: name,
  198. }
  199. l := &profile.Location{
  200. ID: uint64(i + 1),
  201. Line: []profile.Line{
  202. {
  203. Function: f,
  204. },
  205. },
  206. }
  207. fv, _ := measurement.Scale(flat, o.SampleUnit, o.OutputUnit)
  208. cv, _ := measurement.Scale(cum, o.SampleUnit, o.OutputUnit)
  209. s := &profile.Sample{
  210. Location: []*profile.Location{l},
  211. Value: []int64{int64(cv), int64(fv)},
  212. }
  213. out.Function = append(out.Function, f)
  214. out.Location = append(out.Location, l)
  215. out.Sample = append(out.Sample, s)
  216. }
  217. return out.Write(w)
  218. }
  219. // printAssembly prints an annotated assembly listing.
  220. func printAssembly(w io.Writer, rpt *Report, obj plugin.ObjTool) error {
  221. o := rpt.options
  222. prof := rpt.prof
  223. g := rpt.newGraph(nil)
  224. // If the regexp source can be parsed as an address, also match
  225. // functions that land on that address.
  226. var address *uint64
  227. if hex, err := strconv.ParseUint(o.Symbol.String(), 0, 64); err == nil {
  228. address = &hex
  229. }
  230. fmt.Fprintln(w, "Total:", rpt.formatValue(rpt.total))
  231. symbols := symbolsFromBinaries(prof, g, o.Symbol, address, obj)
  232. symNodes := nodesPerSymbol(g.Nodes, symbols)
  233. // Sort function names for printing.
  234. var syms objSymbols
  235. for s := range symNodes {
  236. syms = append(syms, s)
  237. }
  238. sort.Sort(syms)
  239. // Correlate the symbols from the binary with the profile samples.
  240. for _, s := range syms {
  241. sns := symNodes[s]
  242. // Gather samples for this symbol.
  243. flatSum, cumSum := sns.Sum()
  244. // Get the function assembly.
  245. insns, err := obj.Disasm(s.sym.File, s.sym.Start, s.sym.End)
  246. if err != nil {
  247. return err
  248. }
  249. ns := annotateAssembly(insns, sns, s.base)
  250. fmt.Fprintf(w, "ROUTINE ======================== %s\n", s.sym.Name[0])
  251. for _, name := range s.sym.Name[1:] {
  252. fmt.Fprintf(w, " AKA ======================== %s\n", name)
  253. }
  254. fmt.Fprintf(w, "%10s %10s (flat, cum) %s of Total\n",
  255. rpt.formatValue(flatSum), rpt.formatValue(cumSum),
  256. percentage(cumSum, rpt.total))
  257. for _, n := range ns {
  258. fmt.Fprintf(w, "%10s %10s %10x: %s\n", valueOrDot(n.Flat, rpt), valueOrDot(n.Cum, rpt), n.Info.Address, n.Info.Name)
  259. }
  260. }
  261. return nil
  262. }
  263. // symbolsFromBinaries examines the binaries listed on the profile
  264. // that have associated samples, and identifies symbols matching rx.
  265. func symbolsFromBinaries(prof *profile.Profile, g *graph.Graph, rx *regexp.Regexp, address *uint64, obj plugin.ObjTool) []*objSymbol {
  266. hasSamples := make(map[string]bool)
  267. // Only examine mappings that have samples that match the
  268. // regexp. This is an optimization to speed up pprof.
  269. for _, n := range g.Nodes {
  270. if name := n.Info.PrintableName(); rx.MatchString(name) && n.Info.Objfile != "" {
  271. hasSamples[n.Info.Objfile] = true
  272. }
  273. }
  274. // Walk all mappings looking for matching functions with samples.
  275. var objSyms []*objSymbol
  276. for _, m := range prof.Mapping {
  277. if !hasSamples[filepath.Base(m.File)] {
  278. if address == nil || !(m.Start <= *address && *address <= m.Limit) {
  279. continue
  280. }
  281. }
  282. f, err := obj.Open(m.File, m.Start, m.Limit, m.Offset)
  283. if err != nil {
  284. fmt.Printf("%v\n", err)
  285. continue
  286. }
  287. // Find symbols in this binary matching the user regexp.
  288. var addr uint64
  289. if address != nil {
  290. addr = *address
  291. }
  292. msyms, err := f.Symbols(rx, addr)
  293. base := f.Base()
  294. f.Close()
  295. if err != nil {
  296. continue
  297. }
  298. for _, ms := range msyms {
  299. objSyms = append(objSyms,
  300. &objSymbol{
  301. sym: ms,
  302. base: base,
  303. },
  304. )
  305. }
  306. }
  307. return objSyms
  308. }
  309. // objSym represents a symbol identified from a binary. It includes
  310. // the SymbolInfo from the disasm package and the base that must be
  311. // added to correspond to sample addresses
  312. type objSymbol struct {
  313. sym *plugin.Sym
  314. base uint64
  315. }
  316. // objSymbols is a wrapper type to enable sorting of []*objSymbol.
  317. type objSymbols []*objSymbol
  318. func (o objSymbols) Len() int {
  319. return len(o)
  320. }
  321. func (o objSymbols) Less(i, j int) bool {
  322. if namei, namej := o[i].sym.Name[0], o[j].sym.Name[0]; namei != namej {
  323. return namei < namej
  324. }
  325. return o[i].sym.Start < o[j].sym.Start
  326. }
  327. func (o objSymbols) Swap(i, j int) {
  328. o[i], o[j] = o[j], o[i]
  329. }
  330. // nodesPerSymbol classifies nodes into a group of symbols.
  331. func nodesPerSymbol(ns graph.Nodes, symbols []*objSymbol) map[*objSymbol]graph.Nodes {
  332. symNodes := make(map[*objSymbol]graph.Nodes)
  333. for _, s := range symbols {
  334. // Gather samples for this symbol.
  335. for _, n := range ns {
  336. address := n.Info.Address - s.base
  337. if address >= s.sym.Start && address < s.sym.End {
  338. symNodes[s] = append(symNodes[s], n)
  339. }
  340. }
  341. }
  342. return symNodes
  343. }
  344. // annotateAssembly annotates a set of assembly instructions with a
  345. // set of samples. It returns a set of nodes to display. base is an
  346. // offset to adjust the sample addresses.
  347. func annotateAssembly(insns []plugin.Inst, samples graph.Nodes, base uint64) graph.Nodes {
  348. // Add end marker to simplify printing loop.
  349. insns = append(insns, plugin.Inst{^uint64(0), "", "", 0})
  350. // Ensure samples are sorted by address.
  351. samples.Sort(graph.AddressOrder)
  352. var s int
  353. var asm graph.Nodes
  354. for ix, in := range insns[:len(insns)-1] {
  355. n := graph.Node{
  356. Info: graph.NodeInfo{
  357. Address: in.Addr,
  358. Name: in.Text,
  359. File: trimPath(in.File),
  360. Lineno: in.Line,
  361. },
  362. }
  363. // Sum all the samples until the next instruction (to account
  364. // for samples attributed to the middle of an instruction).
  365. for next := insns[ix+1].Addr; s < len(samples) && samples[s].Info.Address-base < next; s++ {
  366. n.Flat += samples[s].Flat
  367. n.Cum += samples[s].Cum
  368. if samples[s].Info.File != "" {
  369. n.Info.File = trimPath(samples[s].Info.File)
  370. n.Info.Lineno = samples[s].Info.Lineno
  371. }
  372. }
  373. asm = append(asm, &n)
  374. }
  375. return asm
  376. }
  377. // valueOrDot formats a value according to a report, intercepting zero
  378. // values.
  379. func valueOrDot(value int64, rpt *Report) string {
  380. if value == 0 {
  381. return "."
  382. }
  383. return rpt.formatValue(value)
  384. }
  385. // canAccessFile determines if the filename can be opened for reading.
  386. func canAccessFile(path string) bool {
  387. if fi, err := os.Stat(path); err == nil {
  388. return fi.Mode().Perm()&0400 != 0
  389. }
  390. return false
  391. }
  392. // printTags collects all tags referenced in the profile and prints
  393. // them in a sorted table.
  394. func printTags(w io.Writer, rpt *Report) error {
  395. p := rpt.prof
  396. // Hashtable to keep accumulate tags as key,value,count.
  397. tagMap := make(map[string]map[string]int64)
  398. for _, s := range p.Sample {
  399. for key, vals := range s.Label {
  400. for _, val := range vals {
  401. if valueMap, ok := tagMap[key]; ok {
  402. valueMap[val] = valueMap[val] + s.Value[0]
  403. continue
  404. }
  405. valueMap := make(map[string]int64)
  406. valueMap[val] = s.Value[0]
  407. tagMap[key] = valueMap
  408. }
  409. }
  410. for key, vals := range s.NumLabel {
  411. for _, nval := range vals {
  412. val := measurement.Label(nval, key)
  413. if valueMap, ok := tagMap[key]; ok {
  414. valueMap[val] = valueMap[val] + s.Value[0]
  415. continue
  416. }
  417. valueMap := make(map[string]int64)
  418. valueMap[val] = s.Value[0]
  419. tagMap[key] = valueMap
  420. }
  421. }
  422. }
  423. tagKeys := make([]*graph.Tag, 0, len(tagMap))
  424. for key := range tagMap {
  425. tagKeys = append(tagKeys, &graph.Tag{Name: key})
  426. }
  427. for _, tagKey := range graph.SortTags(tagKeys, true) {
  428. var total int64
  429. key := tagKey.Name
  430. tags := make([]*graph.Tag, 0, len(tagMap[key]))
  431. for t, c := range tagMap[key] {
  432. total += c
  433. tags = append(tags, &graph.Tag{Name: t, Flat: c})
  434. }
  435. fmt.Fprintf(w, "%s: Total %d\n", key, total)
  436. for _, t := range graph.SortTags(tags, true) {
  437. if total > 0 {
  438. fmt.Fprintf(w, " %8d (%s): %s\n", t.Flat,
  439. percentage(t.Flat, total), t.Name)
  440. } else {
  441. fmt.Fprintf(w, " %8d: %s\n", t.Flat, t.Name)
  442. }
  443. }
  444. fmt.Fprintln(w)
  445. }
  446. return nil
  447. }
  448. // printText prints a flat text report for a profile.
  449. func printText(w io.Writer, rpt *Report) error {
  450. g, origCount, droppedNodes, _ := rpt.newTrimmedGraph()
  451. rpt.selectOutputUnit(g)
  452. fmt.Fprintln(w, strings.Join(reportLabels(rpt, g, origCount, droppedNodes, 0, false), "\n"))
  453. fmt.Fprintf(w, "%10s %5s%% %5s%% %10s %5s%%\n",
  454. "flat", "flat", "sum", "cum", "cum")
  455. var flatSum int64
  456. for _, n := range g.Nodes {
  457. name, flat, cum := n.Info.PrintableName(), n.Flat, n.Cum
  458. var inline, noinline bool
  459. for _, e := range n.In {
  460. if e.Inline {
  461. inline = true
  462. } else {
  463. noinline = true
  464. }
  465. }
  466. if inline {
  467. if noinline {
  468. name = name + " (partial-inline)"
  469. } else {
  470. name = name + " (inline)"
  471. }
  472. }
  473. flatSum += flat
  474. fmt.Fprintf(w, "%10s %s %s %10s %s %s\n",
  475. rpt.formatValue(flat),
  476. percentage(flat, rpt.total),
  477. percentage(flatSum, rpt.total),
  478. rpt.formatValue(cum),
  479. percentage(cum, rpt.total),
  480. name)
  481. }
  482. return nil
  483. }
  484. // printTraces prints all traces from a profile.
  485. func printTraces(w io.Writer, rpt *Report) error {
  486. fmt.Fprintln(w, strings.Join(ProfileLabels(rpt), "\n"))
  487. prof := rpt.prof
  488. o := rpt.options
  489. const separator = "-----------+-------------------------------------------------------"
  490. locations := graph.NewLocInfo(prof, false)
  491. for _, sample := range prof.Sample {
  492. var stack []graph.NodeInfo
  493. for _, loc := range sample.Location {
  494. id := loc.ID
  495. stack = append(stack, locations[id]...)
  496. }
  497. if len(stack) == 0 {
  498. continue
  499. }
  500. fmt.Fprintln(w, separator)
  501. // Print any text labels for the sample.
  502. var labels []string
  503. for s, vs := range sample.Label {
  504. labels = append(labels, fmt.Sprintf("%10s: %s\n", s, strings.Join(vs, " ")))
  505. }
  506. sort.Strings(labels)
  507. fmt.Fprint(w, strings.Join(labels, ""))
  508. // Print call stack.
  509. fmt.Fprintf(w, "%10s %s\n",
  510. rpt.formatValue(o.SampleValue(sample.Value)),
  511. stack[0].PrintableName())
  512. for _, s := range stack[1:] {
  513. fmt.Fprintf(w, "%10s %s\n", "", s.PrintableName())
  514. }
  515. }
  516. fmt.Fprintln(w, separator)
  517. return nil
  518. }
  519. // printCallgrind prints a graph for a profile on callgrind format.
  520. func printCallgrind(w io.Writer, rpt *Report) error {
  521. o := rpt.options
  522. rpt.options.NodeFraction = 0
  523. rpt.options.EdgeFraction = 0
  524. rpt.options.NodeCount = 0
  525. g, _, _, _ := rpt.newTrimmedGraph()
  526. rpt.selectOutputUnit(g)
  527. fmt.Fprintln(w, "events:", o.SampleType+"("+o.OutputUnit+")")
  528. files := make(map[string]int)
  529. names := make(map[string]int)
  530. for _, n := range g.Nodes {
  531. fmt.Fprintln(w, "fl="+callgrindName(files, n.Info.File))
  532. fmt.Fprintln(w, "fn="+callgrindName(names, n.Info.Name))
  533. sv, _ := measurement.Scale(n.Flat, o.SampleUnit, o.OutputUnit)
  534. fmt.Fprintf(w, "%d %d\n", n.Info.Lineno, int64(sv))
  535. // Print outgoing edges.
  536. for _, out := range n.Out.Sort() {
  537. c, _ := measurement.Scale(out.Weight, o.SampleUnit, o.OutputUnit)
  538. callee := out.Dest
  539. fmt.Fprintln(w, "cfl="+callgrindName(files, callee.Info.File))
  540. fmt.Fprintln(w, "cfn="+callgrindName(names, callee.Info.Name))
  541. // pprof doesn't have a flat weight for a call, leave as 0.
  542. fmt.Fprintln(w, "calls=0", callee.Info.Lineno)
  543. fmt.Fprintln(w, n.Info.Lineno, int64(c))
  544. }
  545. fmt.Fprintln(w)
  546. }
  547. return nil
  548. }
  549. // callgrindName implements the callgrind naming compression scheme.
  550. // For names not previously seen returns "(N) name", where N is a
  551. // unique index. For names previously seen returns "(N)" where N is
  552. // the index returned the first time.
  553. func callgrindName(names map[string]int, name string) string {
  554. if name == "" {
  555. return ""
  556. }
  557. if id, ok := names[name]; ok {
  558. return fmt.Sprintf("(%d)", id)
  559. }
  560. id := len(names) + 1
  561. names[name] = id
  562. return fmt.Sprintf("(%d) %s", id, name)
  563. }
  564. // printTree prints a tree-based report in text form.
  565. func printTree(w io.Writer, rpt *Report) error {
  566. const separator = "----------------------------------------------------------+-------------"
  567. const legend = " flat flat% sum% cum cum% calls calls% + context "
  568. g, origCount, droppedNodes, _ := rpt.newTrimmedGraph()
  569. rpt.selectOutputUnit(g)
  570. fmt.Fprintln(w, strings.Join(reportLabels(rpt, g, origCount, droppedNodes, 0, false), "\n"))
  571. fmt.Fprintln(w, separator)
  572. fmt.Fprintln(w, legend)
  573. var flatSum int64
  574. rx := rpt.options.Symbol
  575. for _, n := range g.Nodes {
  576. name, flat, cum := n.Info.PrintableName(), n.Flat, n.Cum
  577. // Skip any entries that do not match the regexp (for the "peek" command).
  578. if rx != nil && !rx.MatchString(name) {
  579. continue
  580. }
  581. fmt.Fprintln(w, separator)
  582. // Print incoming edges.
  583. inEdges := n.In.Sort()
  584. for _, in := range inEdges {
  585. var inline string
  586. if in.Inline {
  587. inline = " (inline)"
  588. }
  589. fmt.Fprintf(w, "%50s %s | %s%s\n", rpt.formatValue(in.Weight),
  590. percentage(in.Weight, cum), in.Src.Info.PrintableName(), inline)
  591. }
  592. // Print current node.
  593. flatSum += flat
  594. fmt.Fprintf(w, "%10s %s %s %10s %s | %s\n",
  595. rpt.formatValue(flat),
  596. percentage(flat, rpt.total),
  597. percentage(flatSum, rpt.total),
  598. rpt.formatValue(cum),
  599. percentage(cum, rpt.total),
  600. name)
  601. // Print outgoing edges.
  602. outEdges := n.Out.Sort()
  603. for _, out := range outEdges {
  604. var inline string
  605. if out.Inline {
  606. inline = " (inline)"
  607. }
  608. fmt.Fprintf(w, "%50s %s | %s%s\n", rpt.formatValue(out.Weight),
  609. percentage(out.Weight, cum), out.Dest.Info.PrintableName(), inline)
  610. }
  611. }
  612. if len(g.Nodes) > 0 {
  613. fmt.Fprintln(w, separator)
  614. }
  615. return nil
  616. }
  617. // printDOT prints an annotated callgraph in DOT format.
  618. func printDOT(w io.Writer, rpt *Report) error {
  619. g, origCount, droppedNodes, droppedEdges := rpt.newTrimmedGraph()
  620. rpt.selectOutputUnit(g)
  621. labels := reportLabels(rpt, g, origCount, droppedNodes, droppedEdges, true)
  622. c := &graph.DotConfig{
  623. Title: rpt.options.Title,
  624. Labels: labels,
  625. FormatValue: rpt.formatValue,
  626. Total: rpt.total,
  627. }
  628. graph.ComposeDot(w, g, &graph.DotAttributes{}, c)
  629. return nil
  630. }
  631. // percentage computes the percentage of total of a value, and encodes
  632. // it as a string. At least two digits of precision are printed.
  633. func percentage(value, total int64) string {
  634. var ratio float64
  635. if total != 0 {
  636. ratio = math.Abs(float64(value)/float64(total)) * 100
  637. }
  638. switch {
  639. case math.Abs(ratio) >= 99.95 && math.Abs(ratio) <= 100.05:
  640. return " 100%"
  641. case math.Abs(ratio) >= 1.0:
  642. return fmt.Sprintf("%5.2f%%", ratio)
  643. default:
  644. return fmt.Sprintf("%5.2g%%", ratio)
  645. }
  646. }
  647. // ProfileLabels returns printable labels for a profile.
  648. func ProfileLabels(rpt *Report) []string {
  649. label := []string{}
  650. prof := rpt.prof
  651. o := rpt.options
  652. if len(prof.Mapping) > 0 {
  653. if prof.Mapping[0].File != "" {
  654. label = append(label, "File: "+filepath.Base(prof.Mapping[0].File))
  655. }
  656. if prof.Mapping[0].BuildID != "" {
  657. label = append(label, "Build ID: "+prof.Mapping[0].BuildID)
  658. }
  659. }
  660. label = append(label, prof.Comments...)
  661. if o.SampleType != "" {
  662. label = append(label, "Type: "+o.SampleType)
  663. }
  664. if prof.TimeNanos != 0 {
  665. const layout = "Jan 2, 2006 at 3:04pm (MST)"
  666. label = append(label, "Time: "+time.Unix(0, prof.TimeNanos).Format(layout))
  667. }
  668. if prof.DurationNanos != 0 {
  669. duration := measurement.Label(prof.DurationNanos, "nanoseconds")
  670. totalNanos, totalUnit := measurement.Scale(rpt.total, o.SampleUnit, "nanoseconds")
  671. var ratio string
  672. if totalUnit == "ns" && totalNanos != 0 {
  673. ratio = "(" + percentage(int64(totalNanos), prof.DurationNanos) + ")"
  674. }
  675. label = append(label, fmt.Sprintf("Duration: %s, Total samples = %s %s", duration, rpt.formatValue(rpt.total), ratio))
  676. }
  677. return label
  678. }
  679. // reportLabels returns printable labels for a report. Includes
  680. // profileLabels.
  681. func reportLabels(rpt *Report, g *graph.Graph, origCount, droppedNodes, droppedEdges int, fullHeaders bool) []string {
  682. nodeFraction := rpt.options.NodeFraction
  683. edgeFraction := rpt.options.EdgeFraction
  684. nodeCount := rpt.options.NodeCount
  685. var label []string
  686. if len(rpt.options.ProfileLabels) > 0 {
  687. for _, l := range rpt.options.ProfileLabels {
  688. label = append(label, l)
  689. }
  690. } else if fullHeaders || !rpt.options.CompactLabels {
  691. label = ProfileLabels(rpt)
  692. }
  693. var flatSum int64
  694. for _, n := range g.Nodes {
  695. flatSum = flatSum + n.Flat
  696. }
  697. 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)))
  698. if rpt.total != 0 {
  699. if droppedNodes > 0 {
  700. label = append(label, genLabel(droppedNodes, "node", "cum",
  701. rpt.formatValue(abs64(int64(float64(rpt.total)*nodeFraction)))))
  702. }
  703. if droppedEdges > 0 {
  704. label = append(label, genLabel(droppedEdges, "edge", "freq",
  705. rpt.formatValue(abs64(int64(float64(rpt.total)*edgeFraction)))))
  706. }
  707. if nodeCount > 0 && nodeCount < origCount {
  708. label = append(label, fmt.Sprintf("Showing top %d nodes out of %d (cum >= %s)",
  709. nodeCount, origCount,
  710. rpt.formatValue(g.Nodes[len(g.Nodes)-1].Cum)))
  711. }
  712. }
  713. return label
  714. }
  715. func genLabel(d int, n, l, f string) string {
  716. if d > 1 {
  717. n = n + "s"
  718. }
  719. return fmt.Sprintf("Dropped %d %s (%s <= %s)", d, n, l, f)
  720. }
  721. // Output formats.
  722. const (
  723. Proto = iota
  724. Dot
  725. Tags
  726. Tree
  727. Text
  728. Traces
  729. Raw
  730. Dis
  731. List
  732. WebList
  733. Callgrind
  734. TopProto
  735. )
  736. // Options are the formatting and filtering options used to generate a
  737. // profile.
  738. type Options struct {
  739. OutputFormat int
  740. CumSort bool
  741. CallTree bool
  742. DropNegative bool
  743. PositivePercentages bool
  744. CompactLabels bool
  745. Ratio float64
  746. Title string
  747. ProfileLabels []string
  748. NodeCount int
  749. NodeFraction float64
  750. EdgeFraction float64
  751. SampleValue func(s []int64) int64
  752. SampleType string
  753. SampleUnit string // Unit for the sample data from the profile.
  754. OutputUnit string // Units for data formatting in report.
  755. Symbol *regexp.Regexp // Symbols to include on disassembly report.
  756. }
  757. // New builds a new report indexing the sample values interpreting the
  758. // samples with the provided function.
  759. func New(prof *profile.Profile, o *Options) *Report {
  760. format := func(v int64) string {
  761. if r := o.Ratio; r > 0 && r != 1 {
  762. fv := float64(v) * r
  763. v = int64(fv)
  764. }
  765. return measurement.ScaledLabel(v, o.SampleUnit, o.OutputUnit)
  766. }
  767. return &Report{prof, computeTotal(prof, o.SampleValue, !o.PositivePercentages),
  768. o, format}
  769. }
  770. // NewDefault builds a new report indexing the last sample value
  771. // available.
  772. func NewDefault(prof *profile.Profile, options Options) *Report {
  773. index := len(prof.SampleType) - 1
  774. o := &options
  775. if o.Title == "" && len(prof.Mapping) > 0 {
  776. o.Title = filepath.Base(prof.Mapping[0].File)
  777. }
  778. o.SampleType = prof.SampleType[index].Type
  779. o.SampleUnit = strings.ToLower(prof.SampleType[index].Unit)
  780. o.SampleValue = func(v []int64) int64 {
  781. return v[index]
  782. }
  783. return New(prof, o)
  784. }
  785. // computeTotal computes the sum of all sample values. This will be
  786. // used to compute percentages. If includeNegative is set, use use
  787. // absolute values to provide a meaningful percentage for both
  788. // negative and positive values. Otherwise only use positive values,
  789. // which is useful when comparing profiles from different jobs.
  790. func computeTotal(prof *profile.Profile, value func(v []int64) int64, includeNegative bool) int64 {
  791. var ret int64
  792. for _, sample := range prof.Sample {
  793. if v := value(sample.Value); v > 0 {
  794. ret += v
  795. } else if includeNegative {
  796. ret -= v
  797. }
  798. }
  799. return ret
  800. }
  801. // Report contains the data and associated routines to extract a
  802. // report from a profile.
  803. type Report struct {
  804. prof *profile.Profile
  805. total int64
  806. options *Options
  807. formatValue func(int64) string
  808. }
  809. func (rpt *Report) formatTags(s *profile.Sample) (string, bool) {
  810. var labels []string
  811. for key, vals := range s.Label {
  812. for _, v := range vals {
  813. labels = append(labels, key+":"+v)
  814. }
  815. }
  816. for key, nvals := range s.NumLabel {
  817. for _, v := range nvals {
  818. labels = append(labels, measurement.Label(v, key))
  819. }
  820. }
  821. if len(labels) == 0 {
  822. return "", false
  823. }
  824. sort.Strings(labels)
  825. return strings.Join(labels, `\n`), true
  826. }
  827. func abs64(i int64) int64 {
  828. if i < 0 {
  829. return -i
  830. }
  831. return i
  832. }