summaryrefslogtreecommitdiff
path: root/tools/intel_gpu_analyze.py
blob: 7189aac4b8e1190edc62e74b15d76b8ab9359414 (plain)
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
#!/usr/bin/python
#
# Intel GPU Top data analyser
#

import sys
import os
import getopt
import tempfile

HEADER="""
<html>
<head>
<title>Analysis for %(title)s</title>
<style>
body {
    font-family: arial;
}

p {
    margin-left: 10px;
}
</style>
</head>

<body>
<h1>Analysis for %(title)s</h1>

<h2>Summary:</h2>
<p>
<h3>Execution lasted %(duration).2f seconds</h3>
"""

PERF_REFERENCE="""
<p>
<a href="%(perf)s">Kernel perf results analysis</a>
</p>
"""

MINMAXAVG="""
<p>
<h3>%(descr)s:</h3>
<b>Minimum:</b> %(min)s <br/>
<b>Maximum:</b> %(max)s <br/>
<b>Average:</b> %(avg)s <br/>
</p>
"""

FIGURE="""
<p>
<hr/>
<a href="%(img)s"><img src="%(img)s" width=800 height=600></a>
<br/>
<b>%(title)s</b>
</p>
"""

PERF_ITERATION="""
<hr/>
<a name="%(sec)d">
<h3>Second %(sec)d</h3>
</a>

Processes in execution: 
"""

PERF_SECOND_TITLE="""
<a href="#%(sec)d">Second %(sec)d</a>
<br/>
"""

PERF_PROCESS_REF="""
<a href="#%(sec)d.%(process)s">%(process)s</a>
"""

PERF_PROCESS="""
<a name="%(sec)d.%(process)s">
<h3>Process %(process)s</h3>
</a>
"""

PERF_TOP="""
<pre>
%(top)s
</pre>
"""

TAIL="""
</body>
</html>
"""

def print_header(output):
    """Prints the header"""
    print >>output, HEADER

def collect(fd):
    """Collects statistics for a given command"""
    columns={}
    results = {}
    while True:
        line = fd.readline()
        if not line:
            break
        line.strip()
        if line[0] == "#":
            # detecting column names
            cols = line[1:].split()
            for pos in range(len(cols)):
                columns[cols[pos]] = pos
            for col in columns:
                results[col] = []
            continue
        data = line.split()
        # fill in results from the headers
        for item in columns.keys():
            pos = columns[item]
            results[item].append(float(data[pos]))
    return results

def analyse_perf(logfile, out_dir, perf="perf.html"):
    """Analyses perf results"""
    perf_data = os.popen("perf script -f comm,pid,time,ip,sym -i %s 2>/dev/null" % logfile)
    if not perf_data:
        print "Error: unable to process perf log %s" % logfile
        return
    results = {}
    time_start = -1
    time_prev = -1
    while 1:
        line = perf_data.readline()
        if not line:
            break
        fields = line.strip().split()
        process = fields[0]
        pid = int(fields[1])
        time = float(fields[2][:-1]) # remove the trailing ':'
        ip = fields[3]
        if len(fields) > 4:
            function = fields[4]
        else:
            function = "unknown"
        # calculate time
        if time_start == -1:
            time_start = int(time) # floor down to the corresponding second
        # are we on the next second already?
        if time - time_start > 1.0:
            time_start = int(time)
        if time_start not in results:
            results[time_start] = {}
        # is the current process being tracked?
        if process not in results[time_start]:
            results[time_start][process]={}
        # calculate times for functions
        if function not in results[time_start][process]:
            results[time_start][process][function] = 0

        # ok, so now calculate per-function per-process stats
        results[time_start][process][function] += (time - time_prev)
        time_prev = time

    # all done, now process the results
    seconds = results.keys()
    seconds.sort()
    output = open("%s/%s" % (out_dir, perf), "w")
    print >>output, HEADER % {'title': 'Perf results for %s' % logfile,
            'duration': len(seconds)
            }
    for sec in seconds:
        # print TOC
        print >>output, PERF_SECOND_TITLE % {'sec': sec - seconds[0]}
    for sec in seconds:
        print >>output, PERF_ITERATION % {'sec': sec - seconds[0], 'processes': ', '.join(results[sec].keys())}
        for process in results[sec]:
            print >>output, PERF_PROCESS_REF % {'sec': sec - seconds[0], 'process': process}
        for process in results[sec]:
            print >>output, PERF_PROCESS % {'sec': sec - seconds[0], 'process': process}
            # let's sort functions
            functions_by_time = sorted(results[sec][process], key=lambda key: results[sec][process][key], reverse=True)
            top = ""
            for function in functions_by_time:
                top += "%.6f\t\t%s\n" % (results[sec][process][function], function)
            print >>output, PERF_TOP % { 'top': top }
    print >>output, TAIL
    output.close()

def analyse(results, title, out_dir, perf_logfile=None, summary="index.html"):
    """Analyses intel_gpu_top results"""
    # calculate min/max/avg values
    keys = results.keys()
    for iter in keys:
        if not results[iter]:
            print "ERROR: no results collected for '%s', aborting" % iter
            sys.exit(1)
        results["%s_min" % iter] = min(results[iter])
        results["%s_max" % iter] = max(results[iter])
        results["%s_avg" % iter] = sum(results[iter]) / len(results[iter])
    # start composing the output
    output = open("%s/%s" % (out_dir, summary), "w")
    print >>output, HEADER % {'title': title,
            'duration': results['time'][-1]
            }

    # print summaries
    for iter, descr in [('utime', 'User time % of CPU'),
            ('stime', 'System time % of CPU'),
            ('power', 'Power consumption (W)'),
            ('render', 'Render engine usage % of GPU'),
            ('render.ops', 'Render engine ops per interval'),
            ('bitstream', 'Bitstream engine usage % of GPU'),
            ('bitstream.ops', 'Bitstream engine ops per interval'),
            ('bitstream6', 'Bitstream 6 engine usage % of GPU'),
            ('bitstream6.ops', 'Bitstream 6 engine ops per interval'),
            ('blitter', 'Blitter engine usage % of GPU'),
            ('blitter.ops', 'Blitter engine ops per interval'),
            ]:
        minval = results['%s_min' % iter]
        maxval = results['%s_max' % iter]
        avgval = results['%s_avg' % iter]
        if minval == maxval == avgval:
            # No variation in data, skipping
            print "No variations in %s, skipping" % iter
            continue
        minval_s = "%.2f" % minval
        maxval_s = "%.2f" % maxval
        avgval_s = "%.2f" % avgval
        print >>output, MINMAXAVG % {
                'descr': descr,
                'min': minval_s,
                'max': maxval_s,
                'avg': avgval_s,
                }

    # Do we have perf results?
    if perf_logfile:
        print >>output, PERF_REFERENCE % {'perf': 'perf.html'}

    # graphics
    try:
        import pylab
    except:
        print "Error: unable to import pylab: %s" % sys.exc_value
        return
    fig = pylab.figure()
    ax = pylab.subplot(111)
    box = ax.get_position()
    pylab.title("Summary of CPU/GPU/Power usage")
    pylab.ylabel("Usage (%)")
    pylab.xlabel("Time (s)")

    ax.plot(results['time'], results['utime'], label="User time")
    ax.plot(results['time'], results['stime'], label="System time")
    num_axis = 2
    for ring in ["render", "bitstream", "bitstream6", "blitter"]:
        if results["%s_avg" % ring] == -1:
            print "No data for %s, skipping" % ring
            continue
        ax.plot(results['time'], results[ring], label=ring)
        num_axis += 1
    # Do we have power?
    if results["power_avg"] != -1:
        # plotting power
        ax2 = ax.twinx()
        ax2.plot(results['time'], results["power"], label="Power (W)", color='red')
        ax2.set_ylabel('Watts')
        ax2.set_position([box.x0, box.y0 + box.height * 0.1, box.width, box.height * 0.9])

    pylab.grid()
    # Shink current axis's height by 10% on the bottom
    ax.set_position([box.x0, box.y0 + box.height * 0.1, box.width, box.height * 0.9])
    ax.legend(loc = 'upper center', ncol=num_axis, fancybox=True, shadow=True, bbox_to_anchor = (0.5, -0.1))
    pylab.savefig("%s/plot_summary.svg" % out_dir, format="svg", dpi=200)
    print >>output, FIGURE % {'img': 'plot_summary.svg',
            'title': 'Summary of the execution, outlining the CPU usage (in user and system mode), per-ring GPU usage, and power usage (if available) '
            }

    # graphics ops/per/second
    fig = pylab.figure()
    ax = pylab.subplot(111)
    pylab.title("GPU rings ops per interval")
    pylab.ylabel("Ops (n)")
    pylab.xlabel("Time (s)")

    num_axis = 0
    for ring in ["render.ops", "bitstream.ops", "bitstream6.ops", "blitter.ops"]:
        if results["%s_avg" % ring] == -1:
            print "No data for %s, skipping" % ring
            continue
        ax.plot(results['time'], results[ring], label=ring)
        num_axis += 1

    pylab.grid()
    # Shink current axis's height by 10% on the bottom
    box = ax.get_position()
    ax.set_position([box.x0, box.y0 + box.height * 0.1, box.width, box.height * 0.9])
    ax.legend(loc = 'upper center', ncol=num_axis, fancybox=True, shadow=True, bbox_to_anchor = (0.5, -0.1))
    pylab.savefig("%s/plot_gpu_ops.svg" % out_dir, format="svg", dpi=200)
    print >>output, FIGURE % {'img': 'plot_gpu_ops.svg',
            'title': 'Ops per interval for each GPU ring during the execution'
            }

    # power
    fig = pylab.figure()
    pylab.title("Power usage summary")
    pylab.ylabel("Power (W)")
    pylab.xlabel("Time (s)")
    ax = pylab.subplot(111)

    ax.plot(results['power'], label="Power")
    ax.plot(results['power.chipset'], label="Chipset")
    ax.plot(results['power.gfx'], label="GFX")
    ax.set_position([box.x0, box.y0 + box.height * 0.1, box.width, box.height * 0.9])
    ax.legend(loc = 'upper center', ncol=3, fancybox=True, shadow=True, bbox_to_anchor = (0.5, -0.1))
    pylab.grid()
    # Shink current axis's height by 10% on the bottom
    pylab.savefig("%s/plot_power.svg" % out_dir, format="svg", dpi=200)
    print >>output, FIGURE % {'img': 'plot_power.svg',
            'title': 'Power usage over the course of execution'
            }

    # power vs CPU
    fig = pylab.figure()
    ax = pylab.subplot(111)
    pylab.title("CPU vs Power usage")
    pylab.ylabel("Usage (%)")
    pylab.xlabel("Time (s)")

    ax.plot(results['time'], results['utime'], label="User time")
    ax.plot(results['time'], results['stime'], label="System time")
    # plotting power
    ax2 = ax.twinx()
    ax2.plot(results['time'], results["power"], label="Power (W)", color='red')
    ax2.set_ylabel('Watts')

    pylab.grid()
    # Shink current axis's height by 10% on the bottom
    box = ax.get_position()
    ax.set_position([box.x0, box.y0 + box.height * 0.1, box.width, box.height * 0.9])
    ax.legend(loc = 'upper center', ncol=3, fancybox=True, shadow=True, bbox_to_anchor = (0.5, -0.1))
    pylab.savefig("%s/plot_power_cpu.svg" % out_dir, format="svg", dpi=200)
    print >>output, FIGURE % {'img': 'plot_power_cpu.svg',
            'title': 'Power utilization co-related to CPU'
            }

    # power vs GPU
    fig = pylab.figure()
    ax = pylab.subplot(111)
    pylab.title("GPU vs Power usage")
    pylab.ylabel("Usage (%)")
    pylab.xlabel("Time (s)")

    num_axis = 0
    for ring in ["render", "bitstream", "bitstream6", "blitter"]:
        if results["%s_avg" % ring] == -1:
            print "No data for %s, skipping" % ring
            continue
        ax.plot(results['time'], results[ring], label=ring)
        num_axis += 1
    # Do we have power?
    # plotting power
    ax2 = ax.twinx()
    ax2.plot(results['time'], results["power"], label="Power (W)", color='red')
    ax2.plot(results['time'], results['power.chipset'], label="Chipset (W)", color='g')
    ax2.plot(results['time'], results['power.gfx'], label="GFX (W)", color='m')
    ax2.set_ylabel('Watts')
    num_axis += 1

    pylab.grid()
    # Shink current axis's height by 10% on the bottom
    box = ax.get_position()
    ax.set_position([box.x0, box.y0 + box.height * 0.1, box.width, box.height * 0.9])
    ax2.set_position([box.x0, box.y0 + box.height * 0.1, box.width, box.height * 0.9])
    ax.legend(loc = 'upper center', ncol=num_axis, fancybox=True, shadow=True, bbox_to_anchor = (0.5, -0.1))
    ax2.legend(loc = 'upper center', ncol=3, fancybox=True, shadow=True, bbox_to_anchor = (0.5, 0.2))
    pylab.savefig("%s/plot_power_gpu.svg" % out_dir, format="svg", dpi=200)
    print >>output, FIGURE % {'img': 'plot_power_gpu.svg',
            'title': 'Power utilization co-related to all GPU rings'
            }

    # per-ring power
    for ring in ["render", "bitstream", "bitstream6", "blitter"]:
        if results["%s_avg" % ring] == -1:
            print "No data for %s, skipping" % ring
            continue
        fig = pylab.figure()
        ax = pylab.subplot(111)
        pylab.title("Power usage vs %s ring" % ring)
        pylab.ylabel("Usage (%)")
        pylab.xlabel("Time (s)")

        ax.plot(results['time'], results[ring], label=ring)
        # Do we have power?
        # plotting power
        ax2 = ax.twinx()
        ax2.plot(results['time'], results["power"], label="Power (W)", color='red')
        ax2.plot(results['time'], results['power.chipset'], label="Chipset", color='g')
        ax2.plot(results['time'], results['power.gfx'], label="GFX", color='m')
        ax2.set_ylabel('Watts')

        pylab.grid()
        # Shink current axis's height by 10% on the bottom
        box = ax.get_position()
        ax.set_position([box.x0, box.y0 + box.height * 0.1, box.width, box.height * 0.9])
        ax2.set_position([box.x0, box.y0 + box.height * 0.1, box.width, box.height * 0.9])
        ax.legend(loc = 'upper center', ncol=1, fancybox=True, shadow=True, bbox_to_anchor = (0.5, -0.1))
        ax2.legend(loc = 'upper center', ncol=3, fancybox=True, shadow=True, bbox_to_anchor = (0.5, 0.2))
        pylab.savefig("%s/plot_power_gpu_%s.svg" % (out_dir, ring), format="svg", dpi=200)
        print >>output, FIGURE % {'img': 'plot_power_gpu_%s.svg' % ring,
                'title': 'Power utilization co-related to the %s ring' % ring
                }

    pass

    print >>output, TAIL
    output.close()

def usage(cmd):
    """Prints usage message"""
    print """Intel-gpu-analyser: intel GPU data analyser

Usage: %s [parameters].

The following arguments are accepted:
    -h, --help          display help message
    -l, --logfile       intel-gpu-top log file to analyse
    -c, --command       command to profile
    -t, --title         description of the command analysed
    -o, --output        output directory for the results
    -p, --perf          kernel perf log file to analyse.

You need to specify either a log file to analyse, or a command to profile,
or a perf log file to process.

When you specify both -l and -c, the last one takes predence.

If you do not give a log file to analyse, or a command to profile, this
tool will become sad, depressed and suicide itself with exit code of -1, and
you will feel bad about it.
"""

if __name__ == "__main__":
    # parse command line
    try:
        opt, args = getopt.getopt(sys.argv[1:], 'hl:c:t:o:p:', ['help', 'logfile=', 'command=', 'title=', 'output=', 'perf='])
    except getopt.error:
        usage(sys.argv[0])
        sys.exit(1)
    logfile = None
    perf_logfile = None
    title = None
    output = os.curdir
    for o in opt:
        # help
        if o[0] == '-h' or o[0] == '--help':
            usage(sys.argv[0])
            sys.exit(0)
        # list
        elif o[0] == '-p' or o[0] == '--perf':
            perf_logfile = o[1]
            print "Analysing perf log file: %s" % perf_logfile
        elif o[0] == '-l' or o[0] == '--logfile':
            logfile = open(o[1], "r")
            title = "Log file '%s'" % o[1]
        elif o[0] == '-c' or o[0] == '--command':
            logfile = os.popen("intel_gpu_top -o - -e \"%s\"" % o[1])
            title = "Execution of '%s'" % o[1]
        # force new level
        elif o[0] == '-t' or o[0] == '--title':
            title = o[1]
        elif o[0] == '-o' or o[0] == '--output':
            output = o[1]
    if not logfile and not perf_logfile:
        usage(sys.argv[0])
        print "Error: no log file and no command to profile, don't know what to do"
        sys.exit(1)
    try:
        os.makedirs(output)
    except:
        pass
    if logfile:
        results = collect(logfile)
        analyse(results, title, output, perf_logfile=perf_logfile)
    if perf_logfile:
        analyse_perf(perf_logfile, output)