forked from andikleen/pmu-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
toplev.py
executable file
·4026 lines (3572 loc) · 142 KB
/
toplev.py
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
#!/usr/bin/env python
# Copyright (c) 2012-2020, Intel Corporation
# Author: Andi Kleen
#
# This program is free software; you can redistribute it and/or modify it
# under the terms and conditions of the GNU General Public License,
# version 2, as published by the Free Software Foundation.
#
# This program is distributed in the hope it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
# more details.
#
# Measure a workload using the topdown performance model:
# estimate on which part of the CPU pipeline it bottlenecks.
#
# Must find ocperf in python module path.
# Handles a variety of perf and kernel versions, but older ones have various
# limitations.
# Environment variables for overrides (see also tl_cpu/ocperf):
# TOPOLOGY=file Read sysfs topology from file. Also --force-topology
# PERF=exe Force perf binary to run
# FORCE_NMI_WATCHDOG=1 Force NMI watchdog mode
# KERNEL_VERSION=... Force kernel version (e.g. 5.0)
# FORCEMETRICS=1 Force fixed metrics and slots
# TLSEED=n Set seed for --subset sample: sampling
# DURATION_TIME=0 Force not using duration_time
# NUM_RUNNERS=n Use n runners to fake hybrid
from __future__ import print_function, division
import sys
import os
import re
import textwrap
import platform
import pty
import subprocess
import argparse
import time
import types
import csv
import bisect
import random
import io
import glob
from copy import copy
from fnmatch import fnmatch
from collections import defaultdict, Counter, OrderedDict
from itertools import compress, groupby, chain
from listutils import cat_unique, dedup, filternot, not_list, append_dict, zip_longest, flatten, findprefix
from objutils import has, safe_ref, map_fields
from tl_stat import ComputeStat, ValStat, combine_valstat
import tl_cpu
import tl_output
import ocperf
import event_download
from tl_uval import UVal
from tl_io import flex_open_r, flex_open_w, popentext
known_cpus = (
("snb", (42, )),
("jkt", (45, )),
("ivb", (58, )),
("ivt", (62, )),
("hsw", (60, 70, 69 )),
("hsx", (63, )),
("slm", (55, 77, 76, )),
("bdw", (61, 71, )),
("bdx", (79, 86, )),
("simple", ()),
("skl", (94, 78, 142, 158, 165, 166, )),
("knl", (87, )),
("skx", ((85, 4,), )),
("clx", ((85, 5,), (85, 6,), (85, 7,), (85, 8,), (85, 9,), (85, 10,), )),
("icl", (126, 125, 157,
167, )), # RKL as ICL for now
("tgl", (140, 141, )),
("icx", (106, 108, )),
)
eventlist_alias = {
140: "GenuineIntel-6-7E", # use ICL list for TGL for now
141: "GenuineIntel-6-7E", # use ICL list for TGL for now
167: "GenuineIntel-6-7E", # use ICL list for RKL for now
}
tsx_cpus = ("hsw", "hsx", "bdw", "skl", "skx", "clx", "icl", "tgl", "icx")
hybrid_cpus = ("adl", )
non_json_events = set(("dummy", "duration_time"))
# handle kernels that don't support all events
unsup_pebs = (
("BR_MISP_RETIRED.ALL_BRANCHES:pp", (("hsw",), (3, 18), None)),
("MEM_LOAD_UOPS_L3_HIT_RETIRED.XSNP_HITM:pp", (("hsw",), (3, 18), None)),
("MEM_LOAD_UOPS_RETIRED.L3_MISS:pp", (("hsw",), (3, 18), None)),
)
ivb_ht_39 = (("ivb", "ivt"), (4, 1), (3, 9))
# uncomment if you removed commit 741a698f420c3 from kernel
#ivb_ht_39 = ((), None, None)
# both kernel bugs and first time a core was supported
# disable events if the kernel does not support them properly
# this does not handle backports (override with --force-events)
unsup_events = (
# commit 36bbb2f2988a29
("OFFCORE_RESPONSE.DEMAND_RFO.L3_HIT.HITM_OTHER_CORE", (("hsw", "hsx"), (3, 18), None)),
# commit 741a698f420c3 broke it, commit e979121b1b and later fixed it
("MEM_LOAD_UOPS_L*_HIT_RETIRED.*", ivb_ht_39),
("MEM_LOAD_UOPS_RETIRED.*", ivb_ht_39),
("MEM_LOAD_UOPS_L*_MISS_RETIRED.*", ivb_ht_39),
("MEM_UOPS_RETIRED.*", ivb_ht_39),
# commit 5e176213a6b2bc
# the event works, but it cannot put into the same group as
# any other CYCLE_ACTIVITY.* event. For now black list, but
# could also special case this in the group scheduler.
("CYCLE_ACTIVITY.STALLS_TOTAL", (("bdw", (4, 4), None))),
# commit 91f1b70582c62576
("CYCLE_ACTIVITY.*", (("bdw"), (4, 1), None)),
("L1D_PEND_MISS.PENDING", (("bdw"), (4, 1), None)),
# commit 6113af14c8
("CYCLE_ACTIVITY:CYCLES_LDM_PENDING", (("ivb", "ivt"), (3, 12), None)),
# commit f8378f52596477
("CYCLE_ACTIVITY.*", (("snb", "jkt"), (3, 9), None)),
# commit 0499bd867bd17c (ULT) or commit 3a632cb229bfb18 (other)
# technically most haswells are 3.10, but ULT is 3.11
("L1D_PEND_MISS.PENDING", (("hsw",), (3, 11), None)),
("L1D_PEND_MISS.PENDING", (("hsx"), (3, 10), None)),
# commit c420f19b9cdc
("CYCLE_ACTIVITY.*_L1D_PENDING", (("hsw", "hsx"), (4, 1), None)),
("CYCLE_ACTIVITY.CYCLES_NO_EXECUTE", (("hsw", "hsx"), (4, 1), None)),
# commit 3a632cb229b
("CYCLE_ACTIVITY.*", (("hsw", "hsx"), (3, 11), None)))
FIXED_BASE = 50
METRICS_BASE = 100
SPECIAL_END = 130
limited_counters_base = {
"instructions": FIXED_BASE + 0,
"cycles": FIXED_BASE + 1,
"ref-cycles": FIXED_BASE + 2,
"slots": FIXED_BASE + 3,
"cpu_core/slots/": FIXED_BASE + 3,
"topdown.slots": FIXED_BASE + 3,
"topdown-fe-bound": METRICS_BASE + 0,
"cpu_core/topdown-fe-bound/": METRICS_BASE + 0,
"topdown-be-bound": METRICS_BASE + 1,
"cpu_core/topdown-be-bound/": METRICS_BASE + 1,
"topdown-bad-spec": METRICS_BASE + 2,
"cpu_core/topdown-bad-spec/": METRICS_BASE + 2,
"topdown-retiring": METRICS_BASE + 3,
"cpu_core/topdown-retiring/": METRICS_BASE + 3,
"cpu/cycles-ct/": 2,
"cpu_core/cycles-ct/": 2,
}
event_nocheck = False
class EventContext(object):
"""Event related context for a given target CPU."""
def __init__(self, pmu):
self.constraint_fixes = dict()
self.errata_whitelist = []
self.outgroup_events = set(["dummy", "duration_time", "msr/tsc/"])
self.sched_ignore_events = set([])
self.require_pebs_events = set([])
self.core_domains = set(["Slots", "CoreClocks", "CoreMetric"])
self.limited_counters = dict(limited_counters_base)
self.limited_set = set(self.limited_counters.keys())
self.fixed_events = set([x for x in self.limited_counters
if FIXED_BASE <= self.limited_counters[x] <= SPECIAL_END])
self.errata_events = dict()
self.errata_warn_events = dict()
self.limit4_events = set()
self.notfound_cache = dict()
self.rmap_cache = dict()
self.slots_available = False
self.emap = None
if pmu is None or pmu not in cpu.counters:
pmu = "cpu"
self.standard_counters = cpu.standard_counters[pmu]
self.counters = cpu.counters[pmu]
self.limit4_counters = cpu.limit4_counters[pmu]
ectx = None
smt_mode = False
test_mode = os.getenv("TL_TESTER")
def warn(msg):
print("warning: " + msg, file=sys.stderr)
if test_mode:
assert 0
warned = set()
def warn_once(msg):
if msg not in warned:
warn(msg)
warned.add(msg)
if test_mode:
assert 0
def warn_once_no_assert(msg):
if msg not in warned:
print("warning: " + msg, file=sys.stderr)
warned.add(msg)
if test_mode:
assert 0
def print_once(msg):
if msg not in warned:
print(msg)
warned.add(msg)
def debug_print(x):
if args.debug:
print(x, file=sys.stderr)
def obj_debug_print(obj, x):
if args.debug or (args.dfilter and obj.name in args.dfilter):
print(x, file=sys.stderr)
def test_debug_print(x):
if args.debug or test_mode:
print(x, file=sys.stderr)
def works(x):
return os.system(x + " >/dev/null 2>/dev/null") == 0
exists_cache = dict()
def cached_exists(fn):
if fn in exists_cache:
return exists_cache[fn]
found = os.path.exists(fn)
exists_cache[fn] = found
return found
class PerfFeatures(object):
"""Adapt to the quirks of various perf versions."""
def __init__(self, args):
pmu = "cpu"
if os.path.exists("/sys/devices/cpu_core"):
pmu = "cpu_core"
self.perf = os.getenv("PERF")
if not self.perf:
self.perf = "perf"
ret = os.system(self.perf + " stat --log-fd 3 3>/dev/null true")
if ret:
# work around the insane perf setup on Debian derivates
# it fails if the perf isn't the same as the kernel
# look for the underlying perf installs, if any
# perf is compatible, so just pick the newest
if ret == 512:
l = sorted(glob.glob("/usr/lib/linux-tools*/perf"),
key=lambda x: [int(t) if t.isdigit() else t for t in re.split(r'(\d+)', x)])
if len(l) > 0:
self.perf = l[0]
ret = os.system(self.perf + " stat --log-fd 3 3>/dev/null true")
if ret:
sys.exit("perf binary is too old/not installed or perf is disabled in /proc/sys/kernel/perf_event_paranoid")
self.logfd_supported = ret == 0
self.supports_power = (
not args.no_uncore
and not args.force_hypervisor
and works(self.perf + " stat -e power/energy-cores/ -a true"))
self.supports_percore = works(self.perf + " stat --percore-show-thread true")
dt = os.getenv("DURATION_TIME")
if dt:
self.supports_duration_time = int(dt)
else:
self.supports_duration_time = works(self.perf + " list duration_time | grep duration_time")
# guests don't support offcore response
if event_nocheck:
self.has_max_precise = True
self.max_precise = 3
else:
self.has_max_precise = os.path.exists("/sys/devices/%s/caps/max_precise" % pmu)
if self.has_max_precise:
self.max_precise = int(open("/sys/devices/%s/caps/max_precise" % pmu).read())
if args.exclusive and not args.print and not works(self.perf + " stat -e '{branches,branches,branches,branches}:e' true"):
sys.exit("perf binary does not support :e exclusive modifier")
def kv_to_key(v):
return v[0] * 100 + v[1]
def unsup_event(e, table, min_kernel=None):
if ":" in e:
e = e[:e.find(":")]
for j in table:
if fnmatch(e, j[0]) and cpu.realcpu in j[1][0]:
break
else:
return False
v = j[1]
if v[1] and kernel_version < kv_to_key(v[1]):
if min_kernel:
min_kernel.append(v[1])
return True
if v[2] and kernel_version >= kv_to_key(v[2]):
return False
return False
def remove_qual(ev):
return re.sub(r':[ku]+', '', re.sub(r'/[ku]+', '/', ev))
def limited_overflow(evlist):
assigned = Counter([ectx.limited_counters[x] for x in evlist if x in ectx.limited_counters]).values()
return any([x > 1 for x in assigned])
# limited to first four counters on ICL+
def limit4_overflow(evlist):
return sum([x in ectx.limit4_events for x in evlist]) > 4
def ismetric(x):
return x.startswith("topdown-") or x.startswith("cpu_core/topdown-")
resources = ("frontend=", "offcore_rsp=", "ldlat=", "in_tx_cp=", "cycles-ct")
def event_to_resource(ev):
for j in resources:
if j in ev:
return j
return ""
def resource_split(evlist):
r = Counter(map(event_to_resource, evlist))
for j in r.keys():
if j == "":
continue
if j == "offcore_rsp=":
if r[j] > 2:
return True
elif r[j] > 1:
return True
return False
def num_generic_counters(evset):
# XXX does not handle formulas having different u/k qualifiers, but we would need to fix the
# callers to be consistent to handle that
return len(evset - set(add_filter(ectx.fixed_events)) - ectx.fixed_events - ectx.outgroup_events - ectx.sched_ignore_events)
FORCE_SPLIT = 100
# Force metrics into own group
metrics_own_group = True
def is_slots(x):
return x in ("slots", "cpu_core/slots/")
def needed_counters(evlist):
evset = set(evlist)
num = num_generic_counters(evset)
evlist = list(map(remove_qual, evlist))
metrics = [ismetric(x) for x in evlist]
if any(metrics):
# slots must be first if metrics are present
if not is_slots(evlist[0]) and any(map(is_slots, evlist)):
debug_print("split for slots %s" % evlist)
return FORCE_SPLIT
# force split if there are other events.
if metrics_own_group and len(evlist) > sum(metrics) + 1:
debug_print("split for other events in topdown %s" % evlist)
return FORCE_SPLIT
# split if any resource is oversubscribed
if resource_split(evlist):
debug_print("resource split %s" % evlist)
return FORCE_SPLIT
evlist = list(compress(evlist, not_list(metrics)))
# force split if we overflow fixed or limited
# some fixed could be promoted to generic, but that doesn't work
# with ref-cycles.
if limited_overflow(evlist):
debug_print("split for limited overflow %s " % evlist)
return FORCE_SPLIT
if limit4_overflow(evlist):
debug_print("split for limit4 overflow %s" % evlist)
return FORCE_SPLIT
return num
def event_group(evlist):
evlist = add_filter(evlist)
l = []
for is_og, g in groupby(evlist, lambda x: x in ectx.outgroup_events):
if is_og or args.no_group:
l += g
else:
g = list(g)
e = ",".join(g)
n = needed_counters(g)
if n <= ectx.counters:
e = "{%s}" % e
if args.exclusive:
e += ":e"
elif args.pinned and all([ismetric(x) or is_slots(x) for x in g]):
e += ":D"
else:
# the scheduler should have avoided that
warn("group %s with %d does not fit in pmu" % (e, n))
l.append(e)
return ",".join(l)
def exe_dir():
d = os.path.realpath(sys.argv[0])
d = os.path.dirname(d)
if d:
return d
return "."
def add_args(rest, *args):
a = [x for x in args if x not in rest]
return a + rest
def update_arg(arg, flag, sep, newval):
i = findprefix(arg, flag, "--")
if i >= 0:
if arg[i] == flag:
arg[i+1] = newval
else:
arg[i] = flag + sep + newval
return True
return False
def del_arg_val(arg, flag):
i = findprefix(arg, flag, "--")
del arg[i:i+2 if arg[i] == flag else i+1]
p = argparse.ArgumentParser(usage='toplev [options] perf-arguments',
description='''
Estimate on which part of the CPU pipeline a workload bottlenecks using the TopDown model.
The bottlenecks are expressed as a tree with different levels.
Requires a modern Intel CPU.
Examples:
toplev.py -l2 program
measure whole system in level 2 while program is running
toplev.py -l1 --single-thread program
measure single threaded program. system must be idle.
toplev.py -l3 --no-desc -I 100 -x, sleep X
measure whole system for X seconds every 100ms, outputting in CSV format.
toplev.py --all --core C0 taskset -c 0,1 program
Measure program running on core 0 with all nodes and metrics enables
''', epilog='''
Other perf arguments allowed (see the perf documentation)
After -- perf arguments conflicting with toplev can be used.
Some caveats:
toplev defaults to measuring the full system and show data
for all CPUs. Use taskset to limit the workload to known CPUs if needed.
In some cases (idle system, single threaded workload) --single-thread
can also be used to get less output.
The lower levels of the measurement tree are less reliable
than the higher levels. They also rely on counter multi-plexing,
and can not run each equation in a single group, which can cause larger
measurement errors with non steady state workloads
(If you don't understand this terminology; it means measurements
in higher levels are less accurate and it works best with programs that primarily
do the same thing over and over)
If the program is very reproducible -- such as a simple kernel --
it is also possible to use --no-multiplex. In this case the
workload is rerun multiple times until all data is collected.
Only use with sleep if the workload is running in a steady state.
With the --drilldown option toplev can automatically remeasure the workload
with only the nodes needed to measure the particular bottlenecks
This also requires a reproducible or steady-state workload.
toplev needs a new enough perf tool and has specific requirements on
the kernel. See http://github.com/andikleen/pmu-tools/wiki/toplev-kernel-support.''',
formatter_class=argparse.RawDescriptionHelpFormatter)
g = p.add_argument_group('General operation')
g.add_argument('--interval', '-I', help='Measure every ms instead of only once',
type=int)
g.add_argument('--no-multiplex',
help='Do not multiplex, but run the workload multiple times as needed. '
'Requires reproducible workloads.',
action='store_true')
g.add_argument('--single-thread', '-S', help='Measure workload as single thread. Workload must run single threaded. '
'In SMT mode other thread must be idle.', action='store_true')
g.add_argument('--fast', '-F', help='Skip sanity checks to optimize CPU consumption', action='store_true')
g.add_argument('--import', help='Import specified perf stat output file instead of running perf. '
'Must be for same cpu, same arguments, same /proc/cpuinfo, same topology, unless overriden',
dest='import_')
g.add_argument('--subset', help="Process only a subset of the input file with --import. "
"Valid syntax: a-b. Process from seek offset a to b. b is optional. "
"x/n%% process x'th n percent slice. Starts counting at 0. Add - to process to end of input. "
"sample:n%% Sample each time stamp in input with n%% (0-100%%) probability. "
"toplev will automatically round to the next time stamp boundary.")
g.add_argument('--parallel',
help="Run toplev --import in parallel in N processes, or the system's number of CPUs if 0 is specified",
action='store_true')
g.add_argument('--pjobs', type=int, default=0,
help='Number of threads to run with parallel. Default is number of CPUs.')
g.add_argument('--gen-script', help='Generate script to collect perfmon information for --import later',
action='store_true')
g.add_argument('--script-record', help='Use perf stat record in script for faster recording or '
'import generated perf.data (requires new perf)', action='store_true')
g.add_argument('--drilldown', help='Automatically rerun to get more details on bottleneck', action='store_true')
g.add_argument('--show-cpu', help='Print current CPU type and exit',
action='store_true')
g = p.add_argument_group('Measurement filtering')
g.add_argument('--kernel', help='Only measure kernel code', action='store_true')
g.add_argument('--user', help='Only measure user code', action='store_true')
g.add_argument('--cpu', '-C', help=argparse.SUPPRESS)
g.add_argument('--pid', '-p', help=argparse.SUPPRESS)
g.add_argument('--core', help='Limit output to cores. Comma list of Sx-Cx-Tx. All parts optional.')
g.add_argument('--no-aggr', '-A', help='Measure every CPU', action='store_true')
g.add_argument('--cputype', help='Limit to hybrid cpu type (atom or core)', choices=['atom', 'core'])
g = p.add_argument_group('Select events')
g.add_argument('--level', '-l', help='Measure upto level N (max 6)',
type=int, default=-1)
g.add_argument('--metrics', '-m', help="Print extra metrics", action='store_true')
g.add_argument('--sw', help="Measure perf Linux metrics", action='store_true')
g.add_argument('--no-util', help="Do not measure CPU utilization", action='store_true')
g.add_argument('--tsx', help="Measure TSX metrics", action='store_true')
g.add_argument('--all', help="Measure everything available", action='store_true')
g.add_argument('--frequency', help="Measure frequency", action='store_true')
g.add_argument('--power', help='Display power metrics', action='store_true')
g.add_argument('--nodes', help='Include or exclude nodes (with + to add, -|^ to remove, '
'comma separated list, wildcards allowed, add * to include all children/siblings, '
'add /level to specify highest level node to match, '
'add ^ to match related siblings and metrics, '
'start with ! to only include specified nodes)')
g.add_argument('--reduced', help='Use reduced server subset of nodes/metrics', action='store_true')
g.add_argument('--metric-group', help='Add (+) or remove (-|^) metric groups of metrics, '
'comma separated list from --list-metric-groups.', default=None)
g.add_argument('--pinned', help='Run topdown metrics (on ICL+) pinned', action='store_true')
g.add_argument('--exclusive', help='Use exclusive groups. Requires new kernel and new perf', action='store_true')
g = p.add_argument_group('Query nodes')
g.add_argument('--list-metrics', help='List all metrics. Can be followed by prefixes to limit, ^ for full match',
action='store_true')
g.add_argument('--list-nodes', help='List all nodes. Can be followed by prefixes to limit, ^ for full match',
action='store_true')
g.add_argument('--list-metric-groups', help='List metric groups.', action='store_true')
g.add_argument('--list-all', help='List every supported node/metric/metricgroup. Can be followed by prefixes to limit, ^ for full match.',
action='store_true')
g.add_argument('--describe', help='Print full descriptions for listed node prefixes. Add ^ to require full match.', action='store_true')
g = p.add_argument_group('Workarounds')
g.add_argument('--no-group', help='Dont use groups', action='store_true')
g.add_argument('--force-events', help='Assume kernel supports all events. May give wrong results.',
action='store_true')
g.add_argument('--ignore-errata', help='Do not disable events with errata', action='store_true', default=True)
g.add_argument('--handle-errata', help='Disable events with errata', action='store_true')
g = p.add_argument_group('Output')
g.add_argument('--per-core', help='Aggregate output per core', action='store_true')
g.add_argument('--per-socket', help='Aggregate output per socket', action='store_true')
g.add_argument('--per-thread', help='Aggregate output per CPU thread', action='store_true')
g.add_argument('--global', help='Aggregate output for all CPUs', action='store_true', dest='global_')
g.add_argument('--no-desc', help='Do not print event descriptions', action='store_true')
g.add_argument('--desc', help='Force event descriptions', action='store_true')
g.add_argument('--verbose', '-v', help='Print all results even when below threshold or exceeding boundaries. '
'Note this can result in bogus values, as the TopDown methodology relies on thresholds '
'to correctly characterize workloads. Values not crossing threshold are marked with <.',
action='store_true')
g.add_argument('--csv', '-x', help='Enable CSV mode with specified delimeter')
g.add_argument('--output', '-o', help='Set output file')
g.add_argument('--split-output', help='Generate multiple output files, one for each specified '
'aggregation option (with -o)',
action='store_true')
g.add_argument('--graph', help='Automatically graph interval output with tl-barplot.py',
action='store_true')
g.add_argument("--graph-cpu", help="CPU to graph using --graph")
g.add_argument('--title', help='Set title of graph')
g.add_argument('--quiet', help='Avoid unnecessary status output', action='store_true')
g.add_argument('--long-desc', help='Print long descriptions instead of abbreviated ones.',
action='store_true')
g.add_argument('--columns', help='Print CPU output in multiple columns for each node', action='store_true')
g.add_argument('--json', help='Print output in JSON format for Chrome about://tracing', action='store_true')
g.add_argument('--summary', help='Print summary at the end. Only useful with -I', action='store_true')
g.add_argument('--no-area', help='Hide area column', action='store_true')
g.add_argument('--perf-output', help='Save perf stat output in specified file')
g.add_argument('--perf-summary', help='Save summarized perf stat output in specified file')
g.add_argument('--no-perf', help=argparse.SUPPRESS, action='store_true') # noop, for compatibility
g.add_argument('--perf', help='Print perf command line', action='store_true')
g.add_argument('--print', help="Only print perf command line. Don't run", action='store_true')
g.add_argument('--idle-threshold', help="Hide idle CPUs (default <5%% of busiest if not CSV, specify percent)",
default=None, type=float)
g.add_argument('--no-output', help="Don't print computed output. Does not affect --summary.", action='store_true')
g.add_argument('--no-mux', help="Don't print mux statistics", action="store_true")
g = p.add_argument_group('Environment')
g.add_argument('--force-cpu', help='Force CPU type', choices=[x[0] for x in known_cpus])
g.add_argument('--force-topology', metavar='findsysoutput', help='Use specified topology file (find /sys/devices)')
g.add_argument('--force-cpuinfo', metavar='cpuinfo', help='Use specified cpuinfo file (/proc/cpuinfo)')
g.add_argument('--force-hypervisor', help='Assume running under hypervisor (no uncore, no offcore, no PEBS)',
action='store_true')
g.add_argument('--no-uncore', help='Disable uncore events', action='store_true')
g.add_argument('--no-check', help='Do not check that PMU units exist', action='store_true')
g = p.add_argument_group('Additional information')
g.add_argument('--print-group', '-g', help='Print event group assignments',
action='store_true')
g.add_argument('--raw', help="Print raw values", action='store_true')
g.add_argument('--valcsv', '-V', help='Write raw counter values into CSV file')
g.add_argument('--stats', help='Show statistics on what events counted', action='store_true')
g = p.add_argument_group('xlsx output')
g.add_argument('--xlsx', help='Generate xlsx spreadsheet output with data for '
'socket/global/thread/core/summary/raw views with 1s interval. '
'Add --single-thread to only get program output.')
g.add_argument('--set-xlsx', help=argparse.SUPPRESS, action='store_true') # set arguments for xlsx only
g.add_argument('--xnormalize', help='Add extra sheets with normalized data in xlsx files', action='store_true')
g.add_argument('--xchart', help='Chart data in xlsx files', action='store_true')
g.add_argument('--keep', help='Keep temporary files', action='store_true')
g.add_argument('--xkeep', dest='keep', action='store_true', help=argparse.SUPPRESS)
g = p.add_argument_group('Sampling')
g.add_argument('--show-sample', help='Show command line to rerun workload with sampling', action='store_true')
g.add_argument('--run-sample', help='Automatically rerun workload with sampling', action='store_true')
g.add_argument('--sample-args', help='Extra arguments to pass to perf record for sampling. Use + to specify -',
default='-g')
g.add_argument('--sample-repeat',
help='Repeat measurement and sampling N times. This interleaves counting and sampling. '
'Useful for background collection with -a sleep X.', type=int)
g.add_argument('--sample-basename', help='Base name of sample perf.data files', default="perf.data")
g.add_argument('-d', help=argparse.SUPPRESS, action='help') # prevent passing this to perf
p.add_argument('--version', help=argparse.SUPPRESS, action='store_true')
p.add_argument('--debug', help=argparse.SUPPRESS, action='store_true') # enable scheduler debugging
p.add_argument('--dfilter', help=argparse.SUPPRESS, action='append')
p.add_argument('--repl', action='store_true', help=argparse.SUPPRESS) # start python repl after initialization
p.add_argument('--filterquals', help=argparse.SUPPRESS, action='store_true') # remove events not supported by perf
p.add_argument('--setvar', help=argparse.SUPPRESS, action='append') # set env variable (for test suite iterating options)
p.add_argument('--tune', nargs='+', help=argparse.SUPPRESS) # override global variables with python expression
p.add_argument('--force-bn', action='append', help=argparse.SUPPRESS) # force bottleneck for testing
p.add_argument('--no-json-header', action='store_true', help=argparse.SUPPRESS) # no [ for json
p.add_argument('--no-json-footer', action='store_true', help=argparse.SUPPRESS) # no ] for json
p.add_argument('--no-csv-header', action='store_true', help=argparse.SUPPRESS) # no header/version for CSV
p.add_argument('--no-csv-footer', action='store_true', help=argparse.SUPPRESS) # no version for CSV
args, rest = p.parse_known_args()
if args.setvar:
for j in args.setvar:
l = j.split("=")
os.environ[l[0]] = l[1]
def output_count():
return args.per_core + args.global_ + args.per_thread + args.per_socket
def multi_output():
return output_count() > 1
def open_output_files():
if args.valcsv:
try:
args.valcsv = flex_open_w(args.valcsv)
except IOError as e:
sys.exit("Cannot open valcsv file %s: %s" % (args.valcsv, e))
if args.perf_output:
try:
args.perf_output = flex_open_w(args.perf_output)
except IOError as e:
sys.exit("Cannot open perf output file %s: %s" % (args.perf_output, e))
def init_xlsx(args):
args.set_xlsx = True
if args.output:
sys.exit("-o / --output not allowed with --xlsx")
if args.valcsv:
sys.exit("--valcsv not allowed with --xlsx")
if args.perf_output:
sys.exit("--perf-output not allowed with --xlsx")
if args.csv:
sys.exit("-c / --csv not allowed with --xlsx")
if not args.xlsx.endswith(".xlsx"):
sys.exit("--xlsx must end in .xlsx")
xlsx_base = re.sub(r'\.xlsx$', '.csv', args.xlsx)
args.valcsv = re.sub(r'\.csv$', '-valcsv.csv', xlsx_base)
args.perf_output = re.sub(r'\.csv$', '-perf.csv', xlsx_base)
args.output = xlsx_base
if args.xchart:
args.xnormalize = True
args.verbose = True
forced_per_socket = False
forced_per_core = False
def set_xlsx(args):
if not args.interval:
args.interval = 1000
args.csv = ','
if args.xlsx:
args.summary = True
if not args.single_thread:
args.per_thread = True
args.split_output = True
global forced_per_socket
if args.per_socket:
forced_per_socket = True
global forced_per_core
if args.per_core:
forced_per_core = True
args.per_socket = True
args.per_core = True
args.no_aggr = True
args.global_ = True
def do_xlsx(env):
cmd = "%s %s/tl-xlsx.py --valcsv '%s' --perf '%s' --cpuinfo '%s' " % (
sys.executable,
exe_dir(),
args.valcsv.name,
args.perf_output.name,
env.cpuinfo if env.cpuinfo else "/proc/cpuinfo")
if args.single_thread:
names = ["program"]
files = [out.logf.name]
else:
names = ((["socket"] if args.per_socket else []) +
(["core"] if args.per_core else []) +
["global", "thread"])
files = [tl_output.output_name(args.output, p) for p in names]
extrafiles = []
extranames = []
charts = []
if args.xnormalize:
for j, n in zip(files, names):
nname = j.replace(".csv", "-norm.csv")
ncmd = "%s %s/interval-normalize.py --normalize-cpu --error-exit < '%s' > '%s'" % (
sys.executable,
exe_dir(),
j,
nname)
if not args.quiet:
print(ncmd)
ret = os.system(ncmd)
if ret:
warn("interval-normalize failed: %d" % ret)
return ret
extrafiles.append(nname)
extranames.append("n" + n)
if args.xchart:
charts.append("n" + n)
cmd += " ".join(["--%s '%s'" % (n, f) for n, f in zip(names, files)])
cmd += " " + " ".join(["--add '%s' '%s'" % (f, n) for n, f in zip(extranames, extrafiles)])
cmd += " " + " ".join(["--chart '%s'" % f for f in charts])
cmd += " '%s'" % args.xlsx
if not args.quiet:
print(cmd)
ret = os.system(cmd)
if not args.keep:
for fn in files + extrafiles:
os.remove(fn)
return ret
def gentmp(o, cpu):
o = re.sub(r'\.(xz|gz)', '', o)
if o.endswith(".csv"):
return o.replace(".csv", "-cpu%d.csv" % cpu)
return o + "-cpu%d" % cpu
def output_to_tmp(arg, outfn):
if not args.output or args.xlsx:
arg.insert(1, "-o" + outfn)
elif update_arg(arg, "--output", "=", outfn):
pass
elif update_arg(arg, "-o", "", outfn):
pass
else:
# does not handle -o combined with other one letter options
sys.exit("Use plain -o / --output argument with --parallel")
def merge_files(files, outf, args):
for j in files:
tl_output.catrmfile(j, outf, args.keep)
# run multiple subset toplevs in parallel and merge the results
def run_parallel(args, env):
procs = []
pofns = []
valfns = []
sums = []
targ = copy(sys.argv)
del targ[targ.index("--parallel")]
ichunk = os.path.getsize(args.import_) / args.pjobs
fileoff = 0
for cpu in range(args.pjobs):
arg = copy(targ)
if args.xlsx:
del_arg_val(arg, "--xlsx")
arg = [arg[0], "--set-xlsx", "--perf-output=X", "--valcsv=X"] + arg[1:]
outfn = gentmp(args.output if args.output else "toplevo%d" % os.getpid(), cpu)
output_to_tmp(arg, outfn)
if args.perf_output or args.xlsx:
pofn = gentmp(args.perf_output if args.perf_output else "toplevp", cpu)
update_arg(arg, "--perf-output", "=", pofn)
pofns.append(pofn)
if args.valcsv or args.xlsx:
valfn = gentmp(args.valcsv if args.valcsv else "toplevv", cpu)
update_arg(arg, "--valcsv", "=", valfn)
valfns.append(valfn)
end = ""
if cpu < args.pjobs-1:
end = "%d" % (fileoff + ichunk)
arg.insert(1, ("--subset=%d-" % fileoff) + end)
fileoff += ichunk
if args.json and args.pjobs > 1:
if cpu > 0:
arg.insert(1, "--no-json-header")
if cpu < args.pjobs - 1 or args.summary:
arg.insert(1, "--no-json-footer")
sumfn = None
if args.summary:
del arg[arg.index("--summary")]
sumfn = gentmp("toplevs%d" % os.getpid(), cpu)
arg.insert(1, "--perf-summary=" + sumfn)
sums.append(sumfn)
if args.pjobs > 1:
if cpu > 0:
arg.insert(1, "--no-csv-header")
if cpu < args.pjobs - 1 or args.summary:
arg.insert(1, "--no-csv-footer")
if not args.quiet:
print(" ".join(arg))
p = subprocess.Popen(arg, stdout=subprocess.PIPE, **popentext)
procs.append((p, outfn))
if args.xlsx:
init_xlsx(args)
set_xlsx(args)
logfiles, logf = tl_output.open_all_logfiles(args, args.output)
for p in procs:
ret = p[0].wait()
if ret:
sys.exit("Subprocess toplev failed %d" % ret)
tl_output.catrmoutput(p[1], logf, logfiles, args.keep)
ret = 0
if sums:
cmd = [sys.executable, exe_dir() + "/interval-merge.py"] + sums
if not args.quiet:
print(" ".join(cmd))
inp = subprocess.Popen(cmd, stdout=subprocess.PIPE)
outfn = "toplevm%d" % os.getpid()
output_to_tmp(targ, outfn)
if args.xlsx:
del_arg_val(targ, "--xlsx")
targ.insert(1, "--set-xlsx")
if args.perf_output:
del_arg_val(targ, "--perf-output")
if args.valcsv:
del_arg_val(targ, "--valcsv")
update_arg(targ, "--import", "=", "/dev/stdin")
targ.insert(1, "--no-output")
if args.json:
targ.insert(1, "--no-json-header")
else:
targ.insert(1, "--no-csv-header")
if not args.quiet:
print(" ".join(targ))
outp = subprocess.Popen(targ, stdin=inp.stdout)
ret = inp.wait()
if ret:
sys.exit("interval-merge failed")
ret = outp.wait()
if ret:
sys.exit("summary toplev failed")
tl_output.catrmoutput(outfn, logf, logfiles, args.keep)
if not args.keep:
for j in sums:
os.remove(j)
open_output_files()
merge_files(valfns, args.valcsv, args)
merge_files(pofns, args.perf_output, args)
if args.xlsx:
ret = do_xlsx(env)
# XXX graph
return ret
if args.idle_threshold:
idle_threshold = args.idle_threshold / 100.
elif args.csv or args.xlsx or args.set_xlsx: # not for args.graph
idle_threshold = 0 # avoid breaking programs that rely on the CSV output
else:
idle_threshold = 0.05
if args.exclusive and args.pinned:
sys.exit("--exclusive and --pinned cannot be combined")
event_nocheck = args.import_ or args.no_check
feat = PerfFeatures(args)
pversion = ocperf.PerfVersion()
def gen_cpu_name(cpu):
if cpu == "simple":
return event_download.get_cpustr()
for j in known_cpus:
if cpu == j[0]:
if isinstance(j[1][0], tuple):
return "GenuineIntel-6-%02X-%d" % j[1][0]
else:
if j[1][0] in eventlist_alias:
return eventlist_alias[j[1][0]]
return "GenuineIntel-6-%02X" % j[1][0]
sys.exit("Unknown cpu %s" % cpu)
return None
if args.tune:
for t in args.tune:
exec(t)
env = tl_cpu.Env()
if args.force_cpu:
env.forcecpu = args.force_cpu
cpuname = gen_cpu_name(args.force_cpu)
if args.force_cpu != "simple":
if not os.getenv("EVENTMAP"):
os.environ["EVENTMAP"] = cpuname
if not os.getenv("UNCORE"):
os.environ["UNCORE"] = cpuname
if args.force_topology:
if not os.getenv("TOPOLOGY"):
os.environ["TOPOLOGY"] = args.force_topology
ocperf.topology = None # force reread
if args.force_cpuinfo:
env.cpuinfo = args.force_cpuinfo
if args.force_hypervisor:
env.hypervisor = True
if args.parallel:
if not args.import_:
sys.exit("--parallel requires --import")
if args.import_.endswith(".xz") or args.import_.endswith(".gz"):
sys.exit("Uncompress input file first") # XXX
if args.perf_summary:
sys.exit("--parallel does not support --perf-summary") # XXX
if args.subset:
# XXX support sample
sys.exit("--parallel does not support --subset")
if args.json and multi_output() and not args.split_output:
sys.exit("--parallel does not support multi-output --json without --split-output")
if args.graph:
sys.exit("--parallel does not support --graph") # XXX
if args.pjobs == 0:
import multiprocessing
args.pjobs = multiprocessing.cpu_count()
sys.exit(run_parallel(args, env))
rest = [x for x in rest if x != "--"]
if args.version:
print("toplev")
sys.exit(0)
if args.cpu:
rest = ["--cpu", args.cpu] + rest
if args.pid:
rest = ["--pid", args.pid] + rest
if args.csv and len(args.csv) != 1:
sys.exit("--csv/-x argument can be only a single character")
if args.xlsx:
init_xlsx(args)
if args.set_xlsx:
set_xlsx(args)
open_output_files()
if args.perf_summary:
try:
args.perf_summary = flex_open_w(args.perf_summary)
except IOError as e:
sys.exit("Cannot open perf summary file %s: %s" % (args.perf_summary, e))
# XXX force no_uncore because the resulting file cannot be imported otherwise?
if args.all:
args.tsx = True
args.power = True