This repository has been archived by the owner on Apr 2, 2019. It is now read-only.
/
report.go
1684 lines (1495 loc) · 41.8 KB
/
report.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package report summarizes a performance profile into a
// human-readable report.
package report
import (
"fmt"
"io"
"math"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
"cmd/internal/pprof/plugin"
"cmd/internal/pprof/profile"
)
// Generate generates a report as directed by the Report.
func Generate(w io.Writer, rpt *Report, obj plugin.ObjTool) error {
o := rpt.options
switch o.OutputFormat {
case Dot:
return printDOT(w, rpt)
case Tree:
return printTree(w, rpt)
case Text:
return printText(w, rpt)
case Raw:
fmt.Fprint(w, rpt.prof.String())
return nil
case Tags:
return printTags(w, rpt)
case Proto:
return rpt.prof.Write(w)
case Dis:
return printAssembly(w, rpt, obj)
case List:
return printSource(w, rpt)
case WebList:
return printWebSource(w, rpt, obj)
case Callgrind:
return printCallgrind(w, rpt)
}
return fmt.Errorf("unexpected output format")
}
// printAssembly prints an annotated assembly listing.
func printAssembly(w io.Writer, rpt *Report, obj plugin.ObjTool) error {
g, err := newGraph(rpt)
if err != nil {
return err
}
o := rpt.options
prof := rpt.prof
// If the regexp source can be parsed as an address, also match
// functions that land on that address.
var address *uint64
if hex, err := strconv.ParseUint(o.Symbol.String(), 0, 64); err == nil {
address = &hex
}
fmt.Fprintln(w, "Total:", rpt.formatValue(rpt.total))
symbols := symbolsFromBinaries(prof, g, o.Symbol, address, obj)
symNodes := nodesPerSymbol(g.ns, symbols)
// Sort function names for printing.
var syms objSymbols
for s := range symNodes {
syms = append(syms, s)
}
sort.Sort(syms)
// Correlate the symbols from the binary with the profile samples.
for _, s := range syms {
sns := symNodes[s]
// Gather samples for this symbol.
flatSum, cumSum := sumNodes(sns)
// Get the function assembly.
insns, err := obj.Disasm(s.sym.File, s.sym.Start, s.sym.End)
if err != nil {
return err
}
ns := annotateAssembly(insns, sns, s.base)
fmt.Fprintf(w, "ROUTINE ======================== %s\n", s.sym.Name[0])
for _, name := range s.sym.Name[1:] {
fmt.Fprintf(w, " AKA ======================== %s\n", name)
}
fmt.Fprintf(w, "%10s %10s (flat, cum) %s of Total\n",
rpt.formatValue(flatSum), rpt.formatValue(cumSum),
percentage(cumSum, rpt.total))
for _, n := range ns {
fmt.Fprintf(w, "%10s %10s %10x: %s\n", valueOrDot(n.flat, rpt), valueOrDot(n.cum, rpt), n.info.address, n.info.name)
}
}
return nil
}
// symbolsFromBinaries examines the binaries listed on the profile
// that have associated samples, and identifies symbols matching rx.
func symbolsFromBinaries(prof *profile.Profile, g graph, rx *regexp.Regexp, address *uint64, obj plugin.ObjTool) []*objSymbol {
hasSamples := make(map[string]bool)
// Only examine mappings that have samples that match the
// regexp. This is an optimization to speed up pprof.
for _, n := range g.ns {
if name := n.info.prettyName(); rx.MatchString(name) && n.info.objfile != "" {
hasSamples[n.info.objfile] = true
}
}
// Walk all mappings looking for matching functions with samples.
var objSyms []*objSymbol
for _, m := range prof.Mapping {
if !hasSamples[filepath.Base(m.File)] {
if address == nil || !(m.Start <= *address && *address <= m.Limit) {
continue
}
}
f, err := obj.Open(m.File, m.Start)
if err != nil {
fmt.Printf("%v\n", err)
continue
}
// Find symbols in this binary matching the user regexp.
var addr uint64
if address != nil {
addr = *address
}
msyms, err := f.Symbols(rx, addr)
base := f.Base()
f.Close()
if err != nil {
continue
}
for _, ms := range msyms {
objSyms = append(objSyms,
&objSymbol{
sym: ms,
base: base,
},
)
}
}
return objSyms
}
// objSym represents a symbol identified from a binary. It includes
// the SymbolInfo from the disasm package and the base that must be
// added to correspond to sample addresses
type objSymbol struct {
sym *plugin.Sym
base uint64
}
// objSymbols is a wrapper type to enable sorting of []*objSymbol.
type objSymbols []*objSymbol
func (o objSymbols) Len() int {
return len(o)
}
func (o objSymbols) Less(i, j int) bool {
if namei, namej := o[i].sym.Name[0], o[j].sym.Name[0]; namei != namej {
return namei < namej
}
return o[i].sym.Start < o[j].sym.Start
}
func (o objSymbols) Swap(i, j int) {
o[i], o[j] = o[j], o[i]
}
// nodesPerSymbol classifies nodes into a group of symbols.
func nodesPerSymbol(ns nodes, symbols []*objSymbol) map[*objSymbol]nodes {
symNodes := make(map[*objSymbol]nodes)
for _, s := range symbols {
// Gather samples for this symbol.
for _, n := range ns {
address := n.info.address - s.base
if address >= s.sym.Start && address < s.sym.End {
symNodes[s] = append(symNodes[s], n)
}
}
}
return symNodes
}
// annotateAssembly annotates a set of assembly instructions with a
// set of samples. It returns a set of nodes to display. base is an
// offset to adjust the sample addresses.
func annotateAssembly(insns []plugin.Inst, samples nodes, base uint64) nodes {
// Add end marker to simplify printing loop.
insns = append(insns, plugin.Inst{
Addr: ^uint64(0),
})
// Ensure samples are sorted by address.
samples.sort(addressOrder)
var s int
var asm nodes
for ix, in := range insns[:len(insns)-1] {
n := node{
info: nodeInfo{
address: in.Addr,
name: in.Text,
file: trimPath(in.File),
lineno: in.Line,
},
}
// Sum all the samples until the next instruction (to account
// for samples attributed to the middle of an instruction).
for next := insns[ix+1].Addr; s < len(samples) && samples[s].info.address-base < next; s++ {
n.flat += samples[s].flat
n.cum += samples[s].cum
if samples[s].info.file != "" {
n.info.file = trimPath(samples[s].info.file)
n.info.lineno = samples[s].info.lineno
}
}
asm = append(asm, &n)
}
return asm
}
// valueOrDot formats a value according to a report, intercepting zero
// values.
func valueOrDot(value int64, rpt *Report) string {
if value == 0 {
return "."
}
return rpt.formatValue(value)
}
// printTags collects all tags referenced in the profile and prints
// them in a sorted table.
func printTags(w io.Writer, rpt *Report) error {
p := rpt.prof
// Hashtable to keep accumulate tags as key,value,count.
tagMap := make(map[string]map[string]int64)
for _, s := range p.Sample {
for key, vals := range s.Label {
for _, val := range vals {
if valueMap, ok := tagMap[key]; ok {
valueMap[val] = valueMap[val] + s.Value[0]
continue
}
valueMap := make(map[string]int64)
valueMap[val] = s.Value[0]
tagMap[key] = valueMap
}
}
for key, vals := range s.NumLabel {
for _, nval := range vals {
val := scaledValueLabel(nval, key, "auto")
if valueMap, ok := tagMap[key]; ok {
valueMap[val] = valueMap[val] + s.Value[0]
continue
}
valueMap := make(map[string]int64)
valueMap[val] = s.Value[0]
tagMap[key] = valueMap
}
}
}
tagKeys := make(tags, 0, len(tagMap))
for key := range tagMap {
tagKeys = append(tagKeys, &tag{name: key})
}
sort.Sort(tagKeys)
for _, tagKey := range tagKeys {
var total int64
key := tagKey.name
tags := make(tags, 0, len(tagMap[key]))
for t, c := range tagMap[key] {
total += c
tags = append(tags, &tag{name: t, weight: c})
}
sort.Sort(tags)
fmt.Fprintf(w, "%s: Total %d\n", key, total)
for _, t := range tags {
if total > 0 {
fmt.Fprintf(w, " %8d (%s): %s\n", t.weight,
percentage(t.weight, total), t.name)
} else {
fmt.Fprintf(w, " %8d: %s\n", t.weight, t.name)
}
}
fmt.Fprintln(w)
}
return nil
}
// printText prints a flat text report for a profile.
func printText(w io.Writer, rpt *Report) error {
g, err := newGraph(rpt)
if err != nil {
return err
}
origCount, droppedNodes, _ := g.preprocess(rpt)
fmt.Fprintln(w, strings.Join(legendDetailLabels(rpt, g, origCount, droppedNodes, 0), "\n"))
fmt.Fprintf(w, "%10s %5s%% %5s%% %10s %5s%%\n",
"flat", "flat", "sum", "cum", "cum")
var flatSum int64
for _, n := range g.ns {
name, flat, cum := n.info.prettyName(), n.flat, n.cum
flatSum += flat
fmt.Fprintf(w, "%10s %s %s %10s %s %s\n",
rpt.formatValue(flat),
percentage(flat, rpt.total),
percentage(flatSum, rpt.total),
rpt.formatValue(cum),
percentage(cum, rpt.total),
name)
}
return nil
}
// printCallgrind prints a graph for a profile on callgrind format.
func printCallgrind(w io.Writer, rpt *Report) error {
g, err := newGraph(rpt)
if err != nil {
return err
}
o := rpt.options
rpt.options.NodeFraction = 0
rpt.options.EdgeFraction = 0
rpt.options.NodeCount = 0
g.preprocess(rpt)
fmt.Fprintln(w, "events:", o.SampleType+"("+o.OutputUnit+")")
files := make(map[string]int)
names := make(map[string]int)
for _, n := range g.ns {
fmt.Fprintln(w, "fl="+callgrindName(files, n.info.file))
fmt.Fprintln(w, "fn="+callgrindName(names, n.info.name))
sv, _ := ScaleValue(n.flat, o.SampleUnit, o.OutputUnit)
fmt.Fprintf(w, "%d %d\n", n.info.lineno, int(sv))
// Print outgoing edges.
for _, out := range sortedEdges(n.out) {
c, _ := ScaleValue(out.weight, o.SampleUnit, o.OutputUnit)
count := fmt.Sprintf("%d", int(c))
callee := out.dest
fmt.Fprintln(w, "cfl="+callgrindName(files, callee.info.file))
fmt.Fprintln(w, "cfn="+callgrindName(names, callee.info.name))
fmt.Fprintln(w, "calls="+count, callee.info.lineno)
fmt.Fprintln(w, n.info.lineno, count)
}
fmt.Fprintln(w)
}
return nil
}
// callgrindName implements the callgrind naming compression scheme.
// For names not previously seen returns "(N) name", where N is a
// unique index. For names previously seen returns "(N)" where N is
// the index returned the first time.
func callgrindName(names map[string]int, name string) string {
if name == "" {
return ""
}
if id, ok := names[name]; ok {
return fmt.Sprintf("(%d)", id)
}
id := len(names) + 1
names[name] = id
return fmt.Sprintf("(%d) %s", id, name)
}
// printTree prints a tree-based report in text form.
func printTree(w io.Writer, rpt *Report) error {
const separator = "----------------------------------------------------------+-------------"
const legend = " flat flat% sum% cum cum% calls calls% + context "
g, err := newGraph(rpt)
if err != nil {
return err
}
origCount, droppedNodes, _ := g.preprocess(rpt)
fmt.Fprintln(w, strings.Join(legendDetailLabels(rpt, g, origCount, droppedNodes, 0), "\n"))
fmt.Fprintln(w, separator)
fmt.Fprintln(w, legend)
var flatSum int64
rx := rpt.options.Symbol
for _, n := range g.ns {
name, flat, cum := n.info.prettyName(), n.flat, n.cum
// Skip any entries that do not match the regexp (for the "peek" command).
if rx != nil && !rx.MatchString(name) {
continue
}
fmt.Fprintln(w, separator)
// Print incoming edges.
inEdges := sortedEdges(n.in)
inSum := inEdges.sum()
for _, in := range inEdges {
fmt.Fprintf(w, "%50s %s | %s\n", rpt.formatValue(in.weight),
percentage(in.weight, inSum), in.src.info.prettyName())
}
// Print current node.
flatSum += flat
fmt.Fprintf(w, "%10s %s %s %10s %s | %s\n",
rpt.formatValue(flat),
percentage(flat, rpt.total),
percentage(flatSum, rpt.total),
rpt.formatValue(cum),
percentage(cum, rpt.total),
name)
// Print outgoing edges.
outEdges := sortedEdges(n.out)
outSum := outEdges.sum()
for _, out := range outEdges {
fmt.Fprintf(w, "%50s %s | %s\n", rpt.formatValue(out.weight),
percentage(out.weight, outSum), out.dest.info.prettyName())
}
}
if len(g.ns) > 0 {
fmt.Fprintln(w, separator)
}
return nil
}
// printDOT prints an annotated callgraph in DOT format.
func printDOT(w io.Writer, rpt *Report) error {
g, err := newGraph(rpt)
if err != nil {
return err
}
origCount, droppedNodes, droppedEdges := g.preprocess(rpt)
prof := rpt.prof
graphname := "unnamed"
if len(prof.Mapping) > 0 {
graphname = filepath.Base(prof.Mapping[0].File)
}
fmt.Fprintln(w, `digraph "`+graphname+`" {`)
fmt.Fprintln(w, `node [style=filled fillcolor="#f8f8f8"]`)
fmt.Fprintln(w, dotLegend(rpt, g, origCount, droppedNodes, droppedEdges))
if len(g.ns) == 0 {
fmt.Fprintln(w, "}")
return nil
}
// Make sure nodes have a unique consistent id.
nodeIndex := make(map[*node]int)
maxFlat := float64(g.ns[0].flat)
for i, n := range g.ns {
nodeIndex[n] = i + 1
if float64(n.flat) > maxFlat {
maxFlat = float64(n.flat)
}
}
var edges edgeList
for _, n := range g.ns {
node := dotNode(rpt, maxFlat, nodeIndex[n], n)
fmt.Fprintln(w, node)
if nodelets := dotNodelets(rpt, nodeIndex[n], n); nodelets != "" {
fmt.Fprint(w, nodelets)
}
// Collect outgoing edges.
for _, e := range n.out {
edges = append(edges, e)
}
}
// Sort edges by frequency as a hint to the graph layout engine.
sort.Sort(edges)
for _, e := range edges {
fmt.Fprintln(w, dotEdge(rpt, nodeIndex[e.src], nodeIndex[e.dest], e))
}
fmt.Fprintln(w, "}")
return nil
}
// percentage computes the percentage of total of a value, and encodes
// it as a string. At least two digits of precision are printed.
func percentage(value, total int64) string {
var ratio float64
if total != 0 {
ratio = float64(value) / float64(total) * 100
}
switch {
case ratio >= 99.95:
return " 100%"
case ratio >= 1.0:
return fmt.Sprintf("%5.2f%%", ratio)
default:
return fmt.Sprintf("%5.2g%%", ratio)
}
}
// dotLegend generates the overall graph label for a report in DOT format.
func dotLegend(rpt *Report, g graph, origCount, droppedNodes, droppedEdges int) string {
label := legendLabels(rpt)
label = append(label, legendDetailLabels(rpt, g, origCount, droppedNodes, droppedEdges)...)
return fmt.Sprintf(`subgraph cluster_L { L [shape=box fontsize=32 label="%s\l"] }`, strings.Join(label, `\l`))
}
// legendLabels generates labels exclusive to graph visualization.
func legendLabels(rpt *Report) []string {
prof := rpt.prof
o := rpt.options
var label []string
if len(prof.Mapping) > 0 {
if prof.Mapping[0].File != "" {
label = append(label, "File: "+filepath.Base(prof.Mapping[0].File))
}
if prof.Mapping[0].BuildID != "" {
label = append(label, "Build ID: "+prof.Mapping[0].BuildID)
}
}
if o.SampleType != "" {
label = append(label, "Type: "+o.SampleType)
}
if prof.TimeNanos != 0 {
const layout = "Jan 2, 2006 at 3:04pm (MST)"
label = append(label, "Time: "+time.Unix(0, prof.TimeNanos).Format(layout))
}
if prof.DurationNanos != 0 {
label = append(label, fmt.Sprintf("Duration: %v", time.Duration(prof.DurationNanos)))
}
return label
}
// legendDetailLabels generates labels common to graph and text visualization.
func legendDetailLabels(rpt *Report, g graph, origCount, droppedNodes, droppedEdges int) []string {
nodeFraction := rpt.options.NodeFraction
edgeFraction := rpt.options.EdgeFraction
nodeCount := rpt.options.NodeCount
label := []string{}
var flatSum int64
for _, n := range g.ns {
flatSum = flatSum + n.flat
}
label = append(label, fmt.Sprintf("%s of %s total (%s)", rpt.formatValue(flatSum), rpt.formatValue(rpt.total), percentage(flatSum, rpt.total)))
if rpt.total > 0 {
if droppedNodes > 0 {
label = append(label, genLabel(droppedNodes, "node", "cum",
rpt.formatValue(int64(float64(rpt.total)*nodeFraction))))
}
if droppedEdges > 0 {
label = append(label, genLabel(droppedEdges, "edge", "freq",
rpt.formatValue(int64(float64(rpt.total)*edgeFraction))))
}
if nodeCount > 0 && nodeCount < origCount {
label = append(label, fmt.Sprintf("Showing top %d nodes out of %d (cum >= %s)",
nodeCount, origCount,
rpt.formatValue(g.ns[len(g.ns)-1].cum)))
}
}
return label
}
func genLabel(d int, n, l, f string) string {
if d > 1 {
n = n + "s"
}
return fmt.Sprintf("Dropped %d %s (%s <= %s)", d, n, l, f)
}
// dotNode generates a graph node in DOT format.
func dotNode(rpt *Report, maxFlat float64, rIndex int, n *node) string {
flat, cum := n.flat, n.cum
labels := strings.Split(n.info.prettyName(), "::")
label := strings.Join(labels, `\n`) + `\n`
flatValue := rpt.formatValue(flat)
if flat > 0 {
label = label + fmt.Sprintf(`%s(%s)`,
flatValue,
strings.TrimSpace(percentage(flat, rpt.total)))
} else {
label = label + "0"
}
cumValue := flatValue
if cum != flat {
if flat > 0 {
label = label + `\n`
} else {
label = label + " "
}
cumValue = rpt.formatValue(cum)
label = label + fmt.Sprintf(`of %s(%s)`,
cumValue,
strings.TrimSpace(percentage(cum, rpt.total)))
}
// Scale font sizes from 8 to 24 based on percentage of flat frequency.
// Use non linear growth to emphasize the size difference.
baseFontSize, maxFontGrowth := 8, 16.0
fontSize := baseFontSize
if maxFlat > 0 && flat > 0 && float64(flat) <= maxFlat {
fontSize += int(math.Ceil(maxFontGrowth * math.Sqrt(float64(flat)/maxFlat)))
}
return fmt.Sprintf(`N%d [label="%s" fontsize=%d shape=box tooltip="%s (%s)"]`,
rIndex,
label,
fontSize, n.info.prettyName(), cumValue)
}
// dotEdge generates a graph edge in DOT format.
func dotEdge(rpt *Report, from, to int, e *edgeInfo) string {
w := rpt.formatValue(e.weight)
attr := fmt.Sprintf(`label=" %s"`, w)
if rpt.total > 0 {
if weight := 1 + int(e.weight*100/rpt.total); weight > 1 {
attr = fmt.Sprintf(`%s weight=%d`, attr, weight)
}
if width := 1 + int(e.weight*5/rpt.total); width > 1 {
attr = fmt.Sprintf(`%s penwidth=%d`, attr, width)
}
}
arrow := "->"
if e.residual {
arrow = "..."
}
tooltip := fmt.Sprintf(`"%s %s %s (%s)"`,
e.src.info.prettyName(), arrow, e.dest.info.prettyName(), w)
attr = fmt.Sprintf(`%s tooltip=%s labeltooltip=%s`,
attr, tooltip, tooltip)
if e.residual {
attr = attr + ` style="dotted"`
}
if len(e.src.tags) > 0 {
// Separate children further if source has tags.
attr = attr + " minlen=2"
}
return fmt.Sprintf("N%d -> N%d [%s]", from, to, attr)
}
// dotNodelets generates the DOT boxes for the node tags.
func dotNodelets(rpt *Report, rIndex int, n *node) (dot string) {
const maxNodelets = 4 // Number of nodelets for alphanumeric labels
const maxNumNodelets = 4 // Number of nodelets for numeric labels
var ts, nts tags
for _, t := range n.tags {
if t.unit == "" {
ts = append(ts, t)
} else {
nts = append(nts, t)
}
}
// Select the top maxNodelets alphanumeric labels by weight
sort.Sort(ts)
if len(ts) > maxNodelets {
ts = ts[:maxNodelets]
}
for i, t := range ts {
weight := rpt.formatValue(t.weight)
dot += fmt.Sprintf(`N%d_%d [label = "%s" fontsize=8 shape=box3d tooltip="%s"]`+"\n", rIndex, i, t.name, weight)
dot += fmt.Sprintf(`N%d -> N%d_%d [label=" %s" weight=100 tooltip="\L" labeltooltip="\L"]`+"\n", rIndex, rIndex, i, weight)
}
// Collapse numeric labels into maxNumNodelets buckets, of the form:
// 1MB..2MB, 3MB..5MB, ...
nts = collapseTags(nts, maxNumNodelets)
sort.Sort(nts)
for i, t := range nts {
weight := rpt.formatValue(t.weight)
dot += fmt.Sprintf(`NN%d_%d [label = "%s" fontsize=8 shape=box3d tooltip="%s"]`+"\n", rIndex, i, t.name, weight)
dot += fmt.Sprintf(`N%d -> NN%d_%d [label=" %s" weight=100 tooltip="\L" labeltooltip="\L"]`+"\n", rIndex, rIndex, i, weight)
}
return dot
}
// graph summarizes a performance profile into a format that is
// suitable for visualization.
type graph struct {
ns nodes
}
// nodes is an ordered collection of graph nodes.
type nodes []*node
// tags represent sample annotations
type tags []*tag
type tagMap map[string]*tag
type tag struct {
name string
unit string // Describe the value, "" for non-numeric tags
value int64
weight int64
}
func (t tags) Len() int { return len(t) }
func (t tags) Swap(i, j int) { t[i], t[j] = t[j], t[i] }
func (t tags) Less(i, j int) bool {
if t[i].weight == t[j].weight {
return t[i].name < t[j].name
}
return t[i].weight > t[j].weight
}
// node is an entry on a profiling report. It represents a unique
// program location. It can include multiple names to represent
// inlined functions.
type node struct {
info nodeInfo // Information associated to this entry.
// values associated to this node.
// flat is exclusive to this node, cum includes all descendents.
flat, cum int64
// in and out contains the nodes immediately reaching or reached by this nodes.
in, out edgeMap
// tags provide additional information about subsets of a sample.
tags tagMap
}
type nodeInfo struct {
name string
origName string
address uint64
file string
startLine, lineno int
inline bool
lowPriority bool
objfile string
parent *node // Used only if creating a calltree
}
func (n *node) addTags(s *profile.Sample, weight int64) {
// Add a tag with all string labels
var labels []string
for key, vals := range s.Label {
for _, v := range vals {
labels = append(labels, key+":"+v)
}
}
if len(labels) > 0 {
sort.Strings(labels)
l := n.tags.findOrAddTag(strings.Join(labels, `\n`), "", 0)
l.weight += weight
}
for key, nvals := range s.NumLabel {
for _, v := range nvals {
label := scaledValueLabel(v, key, "auto")
l := n.tags.findOrAddTag(label, key, v)
l.weight += weight
}
}
}
func (m tagMap) findOrAddTag(label, unit string, value int64) *tag {
if l := m[label]; l != nil {
return l
}
l := &tag{
name: label,
unit: unit,
value: value,
}
m[label] = l
return l
}
// collapseTags reduces the number of entries in a tagMap by merging
// adjacent nodes into ranges. It uses a greedy approach to merge
// starting with the entries with the lowest weight.
func collapseTags(ts tags, count int) tags {
if len(ts) <= count {
return ts
}
sort.Sort(ts)
tagGroups := make([]tags, count)
for i, t := range ts[:count] {
tagGroups[i] = tags{t}
}
for _, t := range ts[count:] {
g, d := 0, tagDistance(t, tagGroups[0][0])
for i := 1; i < count; i++ {
if nd := tagDistance(t, tagGroups[i][0]); nd < d {
g, d = i, nd
}
}
tagGroups[g] = append(tagGroups[g], t)
}
var nts tags
for _, g := range tagGroups {
l, w := tagGroupLabel(g)
nts = append(nts, &tag{
name: l,
weight: w,
})
}
return nts
}
func tagDistance(t, u *tag) float64 {
v, _ := ScaleValue(u.value, u.unit, t.unit)
if v < float64(t.value) {
return float64(t.value) - v
}
return v - float64(t.value)
}
func tagGroupLabel(g tags) (string, int64) {
if len(g) == 1 {
t := g[0]
return scaledValueLabel(t.value, t.unit, "auto"), t.weight
}
min := g[0]
max := g[0]
w := min.weight
for _, t := range g[1:] {
if v, _ := ScaleValue(t.value, t.unit, min.unit); int64(v) < min.value {
min = t
}
if v, _ := ScaleValue(t.value, t.unit, max.unit); int64(v) > max.value {
max = t
}
w += t.weight
}
return scaledValueLabel(min.value, min.unit, "auto") + ".." +
scaledValueLabel(max.value, max.unit, "auto"), w
}
// sumNodes adds the flat and sum values on a report.
func sumNodes(ns nodes) (flat int64, cum int64) {
for _, n := range ns {
flat += n.flat
cum += n.cum
}
return
}
type edgeMap map[*node]*edgeInfo
// edgeInfo contains any attributes to be represented about edges in a graph/
type edgeInfo struct {
src, dest *node
// The summary weight of the edge
weight int64
// residual edges connect nodes that were connected through a
// separate node, which has been removed from the report.
residual bool
}
// bumpWeight increases the weight of an edge. If there isn't such an
// edge in the map one is created.
func bumpWeight(from, to *node, w int64, residual bool) {
if from.out[to] != to.in[from] {
panic(fmt.Errorf("asymmetric edges %v %v", *from, *to))
}
if n := from.out[to]; n != nil {
n.weight += w
if n.residual && !residual {
n.residual = false
}
return
}
info := &edgeInfo{src: from, dest: to, weight: w, residual: residual}
from.out[to] = info
to.in[from] = info
}
// Output formats.
const (
Proto = iota
Dot
Tags
Tree
Text
Raw
Dis
List
WebList
Callgrind
)
// Options are the formatting and filtering options used to generate a
// profile.
type Options struct {
OutputFormat int
CumSort bool
CallTree bool
PrintAddresses bool
DropNegative bool
Ratio float64
NodeCount int
NodeFraction float64
EdgeFraction float64
SampleType string
SampleUnit string // Unit for the sample data from the profile.
OutputUnit string // Units for data formatting in report.
Symbol *regexp.Regexp // Symbols to include on disassembly report.
}
// newGraph summarizes performance data from a profile into a graph.
func newGraph(rpt *Report) (g graph, err error) {
prof := rpt.prof
o := rpt.options
// Generate a tree for graphical output if requested.
buildTree := o.CallTree && o.OutputFormat == Dot
locations := make(map[uint64][]nodeInfo)
for _, l := range prof.Location {
locations[l.ID] = newLocInfo(l)
}
nm := make(nodeMap)
for _, sample := range prof.Sample {
if sample.Location == nil {
continue
}
// Construct list of node names for sample.
var stack []nodeInfo
for _, loc := range sample.Location {
id := loc.ID
stack = append(stack, locations[id]...)
}
// Upfront pass to update the parent chains, to prevent the
// merging of nodes with different parents.
if buildTree {
var nn *node
for i := len(stack); i > 0; i-- {
n := &stack[i-1]
n.parent = nn
nn = nm.findOrInsertNode(*n)
}
}
leaf := nm.findOrInsertNode(stack[0])
weight := rpt.sampleValue(sample)
leaf.addTags(sample, weight)
// Aggregate counter data.
leaf.flat += weight
seen := make(map[*node]bool)
var nn *node
for _, s := range stack {
n := nm.findOrInsertNode(s)
if !seen[n] {
seen[n] = true
n.cum += weight
if nn != nil {
bumpWeight(n, nn, weight, false)