forked from andikleen/pmu-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tl_output.py
536 lines (475 loc) · 18.5 KB
/
tl_output.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
# 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.
#
# Output toplev results in various formats
from __future__ import print_function
import locale
import csv
import re
import sys
import json
import os
from math import isnan
from collections import defaultdict, Counter, OrderedDict
from tl_uval import UVal, combine_uval
from tl_io import flex_open_w
if sys.version_info.major == 3:
import typing # noqa
from typing import DefaultDict, Dict, Any # noqa
def output_name(name, typ):
if typ:
if "." in name:
name = re.sub(r'(.*)\.', r'\1-%s.' % typ, name)
else:
name = "-" typ
return name
def open_logfile(name, typ):
if name is None or name == "":
return sys.stderr
if 'write' in name.__class__.__dict__:
return name
name = output_name(name, typ)
try:
return flex_open_w(name)
except IOError:
sys.exit("Cannot open logfile %s" % name)
def open_all_logfiles(args, logfile):
if args.split_output and args.per_thread args.per_core args.per_socket args.global_ > 0:
logfiles = dict()
if args.per_thread:
logfiles['thread'] = open_logfile(logfile, "thread")
if args.per_core:
logfiles['core'] = open_logfile(logfile, "core")
if args.per_socket:
logfiles['socket'] = open_logfile(logfile, "socket")
if args.global_:
logfiles['global'] = open_logfile(logfile, "global")
return logfiles, None
else:
return None, open_logfile(logfile, None)
BUFS = 1024*1024
def catrmfile(infn, outf, keep):
with open(infn, "r") as inf:
while True:
buf = inf.read(BUFS)
if len(buf) == 0:
break
outf.write(buf)
outf.flush()
if not keep:
os.remove(infn)
def catrmoutput(infn, logf, logfiles, keep):
if logfiles:
for j in logfiles.keys():
catrmfile(output_name(infn, j), logfiles[j], keep)
else:
catrmfile(infn, logf, keep)
class Output(object):
"""Abstract base class for Output classes."""
def __init__(self, logfile, version, cpu, args):
self.logfiles, self.logf = open_all_logfiles(args, args.output)
self.printed_descs = set()
self.hdrlen = 30
self.version = version
self.unitlen = 12
self.belowlen = 0
self.version = "%s on %s [%s%s]" % (version, cpu.name, cpu.true_name,
"/" cpu.pmu_name if cpu.pmu_name else "")
self.curname = ""
self.curname_nologf = ""
self.printedversion = set()
self.no_header = args.no_csv_header
self.no_footer = args.no_csv_footer
self.abbrev = args.abbrev
self.valcsv = None
self.last_prefix = ""
self.args = args
def flushfiles(self):
if self.logfiles:
for j in self.logfiles.values():
j.flush()
self.logf.flush()
# pass all possible hdrs in advance to compute suitable padding
def set_hdr(self, hdr, area):
if area:
hdr = "%-16s %s" % (area, hdr)
self.hdrlen = max(len(hdr) 1, self.hdrlen)
def set_below(self, below):
if below:
self.belowlen = 1
def set_unit(self, unit):
self.unitlen = max(len(unit), self.unitlen)
def set_cpus(self, cpus):
pass
def item(self, area, name, uval, timestamp, unit, desc, title, sample, bn, below, idle):
assert isinstance(uval, UVal)
# --
if desc in self.printed_descs:
desc = ""
else:
self.printed_descs.add(desc)
if not area:
area = ""
self.show(timestamp, title, area, name, uval, unit, desc, sample, bn, below, idle)
def ratio(self, area, name, uval, timestamp, unit, desc, title, sample, bn, below, idle):
uval.is_ratio = True
self.item(area, name, uval, timestamp, unit, desc, title, sample, bn, below, idle)
def metric(self, area, name, uval, timestamp, desc, title, unit, idle):
self.item(area, name, uval, timestamp, unit, desc, title, None, "", "", idle)
def flush(self):
pass
def remark(self, m):
if not self.logfiles:
self.logf.write('\n%s:\n' % m)
def reset(self, name):
if self.logfiles:
self.logf = self.logfiles[name]
self.curname = name
self.curname_nologf = name
def show(self, timestamp, title, area, hdr, val, unit, desc, sample, bn, below, idle):
pass
def print_version(self):
if self.no_header or self.args.no_version:
return
if self.curname not in self.printedversion:
if self.logfiles:
self.logfiles[self.curname].write("# " self.version "\n")
else:
self.logf.write("# " self.version "\n")
self.printedversion.add(self.curname)
print_header = print_version
def print_footer(self):
pass
def print_footer_all(self):
if self.no_footer or self.args.no_version:
return
if self.logfiles:
for f in self.logfiles.values():
f.write("# %s\n" % self.version)
else:
self.logf.write("# " self.version "\n")
def fmt_below(below):
if below:
return "<"
return ""
def short_hdr(hdr, last):
n = os.path.commonprefix((hdr, last))
if "." not in n:
return hdr
n = n[:n.rfind(".")]
return "..." hdr[len(n) 1:]
class OutputHuman(Output):
"""Generate human readable single-column output."""
def __init__(self, logfile, args, version, cpu):
Output.__init__(self, logfile, version, cpu, args)
try:
locale.setlocale(locale.LC_ALL, '')
except locale.Error:
pass
self.args = args
self.titlelen = 7
def set_cpus(self, cpus):
if len(cpus) > 0:
self.titlelen = max(map(len, cpus)) 1
def print_desc(self, desc, sample):
if self.args.no_desc:
return
if desc:
print("\t" desc, file=self.logf)
if sample:
print("\t" "Sampling events: ", sample, file=self.logf)
def print_timestamp(self, timestamp):
if timestamp:
if isnan(timestamp):
self.logf.write("%-11s " % "SUMMARY")
else:
self.logf.write("%6.9f " % timestamp)
def print_line_header(self, area, ohdr):
if "Info" in area or not self.abbrev:
hdr = ohdr
else:
hdr = short_hdr(ohdr, self.last_prefix)
self.last_prefix = ohdr
if area:
hdr = "%-16s %s" % (area, hdr)
self.logf.write("%-*s " % (self.hdrlen, hdr))
# timestamp Timestamp in interval mode
# title CPU
# area FE/BE ...
# hdr Node Name
# val Formatted measured value
# unit unit
# desc Object description
# sample Sample Objects (string)
# vs Statistics object
# bn marker for bottleneck
# below True if below
# idle Idle marker (ignored for Human)
# Example:
# C0 BE Backend_Bound: 62.00 %
def show(self, timestamp, title, area, hdr, val, unit, desc, sample, bn, below, idle):
self.print_header()
self.print_timestamp(timestamp)
write = self.logf.write
if title:
write("%-*s" % (self.titlelen, title))
self.print_line_header(area, hdr)
vals = "{:<{unitlen}} {:>20} {:<{belowlen}}".format(
(" " if unit and unit[0] != "%" else "") unit,
val.format_value(unit),
fmt_below(below),
unitlen=self.unitlen 2,
belowlen=self.belowlen)
if not self.args.no_mux and val.multiplex != 100.0:
vals = " " val.format_mux()
if val.stddev:
vals = " - {:>8}".format(val.format_uncertainty())
if bn:
vals = bn
write(vals "\n")
self.print_desc(desc, sample)
def metric(self, area, name, uval, timestamp, desc, title, unit, idle):
self.item(area, name, uval, timestamp, unit, desc, title, None, "", "", False)
def convert_ts(ts):
if isnan(ts):
return "SUMMARY"
return ts
class OutputColumns(OutputHuman):
"""Human-readable output data in per-cpu columns."""
def __init__(self, logfile, args, version, cpu):
OutputHuman.__init__(self, logfile, args, version, cpu)
self.nodes = {}
self.timestamp = None
self.cpunames = set()
self.printed_header = False
def set_cpus(self, cpus):
self.cpunames = cpus
def show(self, timestamp, title, area, hdr, val, unit, desc, sample, bn, below, idle):
if self.args.single_thread:
OutputHuman.show(self, timestamp, title, area, hdr, val, unit, desc, sample, bn, below, idle)
return
self.print_header()
self.timestamp = timestamp
key = (area, hdr)
if key not in self.nodes:
self.nodes[key] = {}
assert title not in self.nodes[key]
self.nodes[key][title] = (val, unit, desc, sample, bn, below, idle)
def flush(self):
VALCOL_LEN = 16
write = self.logf.write
cpunames = sorted(self.cpunames)
if not self.printed_header:
if self.timestamp:
write("%9s" % "")
self.print_line_header("", "")
for j in cpunames:
write("%*s " % (VALCOL_LEN, j))
write("\n")
self.printed_header = True
for key in sorted(sorted(self.nodes.keys(), key=lambda x: x[1]), key=lambda x: x[0] == ""):
node = self.nodes[key]
desc = None
sample = None
unit = None
if self.timestamp:
self.print_timestamp(self.timestamp)
self.print_line_header(key[0], key[1])
vlist = []
for cpuname in cpunames:
if cpuname in node:
cpu = node[cpuname]
uval, unit, desc, sample, bn, below, idle = cpu
v = uval.format_value(unit)
vlist.append(uval)
write("%*s%s " % (VALCOL_LEN, v, "?" if below else "*" if bn else " "))
else:
write("%*s " % (VALCOL_LEN, ""))
if unit:
# XXX should move this to be per entry?
cval = combine_uval(vlist)
vs = (" - " cval.format_uncertainty() " " cval.format_mux()) if cval.stddev else ""
write(" %-*s%s" % (self.unitlen, (" " if unit[0] != "%" else "") unit, vs))
write("\n")
self.print_desc(desc, sample)
self.nodes = {}
def reset(self, name):
Output.reset(self, name)
self.printed_header = False
class OutputColumnsCSV(OutputColumns):
"""Columns output in CSV mode."""
def __init__(self, logfile, sep, args, version, cpu):
OutputColumns.__init__(self, logfile, args, version, cpu)
self.writer = {}
if self.logfiles:
for n, f in self.logfiles.items():
self.writer[n] = csv.writer(f, delimiter=sep, lineterminator='\n')
else:
self.writer[''] = csv.writer(self.logf, delimiter=sep, lineterminator='\n')
self.printed_header = False
# XXX implement bn and idle
def show(self, timestamp, title, area, hdr, val, unit, desc, sample, bn, below, idle):
self.print_header()
self.timestamp = timestamp
key = (area, hdr)
if key not in self.nodes:
self.nodes[key] = {}
assert title not in self.nodes[key]
self.nodes[key][title] = (val, unit " " fmt_below(below), desc, sample)
def flush(self):
cpunames = sorted(self.cpunames)
if not self.printed_header and not self.no_header:
ts = ["Timestamp"] if self.timestamp else []
header = ts ["Area", "Node"] cpunames ["Description", "Sample", "Stddev", "Multiplex"]
self.writer[self.curname].writerow([x for x in header])
self.printed_header = True
for key in sorted(sorted(self.nodes.keys(), key=lambda x: x[1]), key=lambda x: x[0] == ""):
node = self.nodes[key]
ts = [convert_ts(self.timestamp)] if self.timestamp else []
l = ts [key[0], key[1]]
vlist = []
ol = {}
desc, sample = "", ""
for cpuname in cpunames:
if cpuname in node:
cpu = node[cpuname]
if cpu[2]:
desc = cpu[2]
desc = re.sub(r"\s ", " ", desc)
if cpu[3]:
sample = cpu[3]
# ignore unit for now
vlist.append(cpu[0])
ol[cpuname] = float(cpu[0].value) if cpu[0].value else ""
else:
vlist.append(UVal("",0))
l = [ol[x] if x in ol else "" for x in cpunames]
l.append(desc)
l.append(sample)
vs = combine_uval(vlist)
if vs:
l = (vs.format_uncertainty().strip(), vs.format_mux().strip())
else:
l = ["", ""]
self.writer[self.curname].writerow(l)
self.nodes = {}
print_footer = Output.print_footer_all
class OutputCSV(Output):
"""Output data in CSV format."""
def __init__(self, logfile, sep, args, version, cpu):
Output.__init__(self, logfile, version, cpu, args)
self.writer = {}
if self.logfiles:
for n, f in self.logfiles.items():
self.writer[n] = csv.writer(f, delimiter=sep, lineterminator='\n')
else:
self.writer[''] = csv.writer(self.logf, delimiter=sep, lineterminator='\n')
self.args = args
self.printed_headers = set()
def print_header(self, timestamp, title):
if self.no_header:
return
if self.curname_nologf not in self.printed_headers:
l = []
if timestamp:
l.append("Timestamp")
if title:
l.append("CPUs")
self.writer[self.curname].writerow(l
['Area', 'Value', 'Unit', 'Description',
'Sample', 'Stddev', 'Multiplex', 'Bottleneck', 'Idle'])
self.printed_headers.add(self.curname_nologf)
def show(self, timestamp, title, area, hdr, val, unit, desc, sample, bn, below, idle):
self.print_header(timestamp, title)
if self.args.no_desc:
desc = ""
desc = re.sub(r"\s ", " ", desc)
l = []
if timestamp:
l.append(convert_ts(timestamp))
if title:
l.append("CPU" title if re.match(r'[0-9] ', title) else title)
stddev = val.format_uncertainty().strip()
multiplex = val.multiplex if not isnan(val.multiplex) else ""
self.writer[self.curname].writerow(l [hdr, val.format_value_raw().strip(),
(unit " " fmt_below(below)).strip(),
desc, sample, stddev, multiplex, bn, "Y" if idle else ""])
print_footer = Output.print_footer_all
class OutputJSON(Output):
"""Output data in chrome / trace-viewer JSON format."""
def __init__(self, logfile, sep, args, version, cpu):
Output.__init__(self, logfile, version, cpu, args)
self.nodes = defaultdict(dict) # type: DefaultDict[str, Dict[str, Any]]
self.headers = OrderedDict()
self.count = Counter() # type: typing.Counter[str]
self.no_header = args.no_json_header
self.no_footer = args.no_json_footer
self.num = 0
def print_footer_all(self):
def write_all(s):
if self.logfiles:
for n in self.logfiles:
self.logfiles[n].write(s(n))
else:
self.logf.write(s(""))
if self.no_footer:
if self.num > 0:
write_all(lambda x: ",\n")
else:
def start(name):
n = ""
if name not in self.count:
n = "[\n"
return n "\n]\n"
write_all(start)
print_footer = print_footer_all
def show(self, timestamp, title, area, hdr, val, unit, desc, sample, bn, below, idle):
self.timestamp = timestamp
self.nodes[title][hdr] = val
self.headers[hdr] = True
self.num = 1
def flush(self):
nodes = OrderedDict() # type: OrderedDict[str,Any]
for hdr in self.headers:
for title in sorted(self.nodes.keys()):
if hdr not in self.nodes[title]:
continue
nd = self.nodes[title]
val = nd[hdr].value if isinstance(nd[hdr], UVal) else nd[hdr]
if title:
title = " "
if hdr in ("Frontend_Bound", "Backend_Bound", "BadSpeculation", "Retiring"): # XXX
key = title "Level1"
if key not in nodes:
nodes[key] = {}
nodes[title "Level1"][hdr] = val
elif hdr.count(".") >= 1:
dot = hdr.rindex(".")
nodes[title hdr[:dot]] = { hdr: round(val, 2) }
else: # assume it's metric
nodes[title hdr] = {hdr: val}
for name in nodes.keys():
if self.count[self.curname] == 0:
if not self.no_header:
self.logf.write("[\n")
else:
self.logf.write(",\n")
json.dump({"name": name,
"ph": "C",
"pid": 0,
"ts": self.timestamp / 1e6 if self.timestamp and not isnan(self.timestamp) else 0,
"args": nodes[name]}, self.logf)
self.count[self.curname] = 1
self.nodes = defaultdict(dict)
self.headers = OrderedDict()
def remark(self, m):
pass