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

import sys
import os
import getopt
import tempfile

# for charts
import pylab

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>
"""

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>
"""

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

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

def collect(fd):
    """Collects statistics for a given command"""
    results = {'time': [],
            'utime': [],
            'stime': [],
            'power': [],
            'render': [],
            'render_ops': [],
            'bitstr': [],
            'bitstr_ops': [],
            'bitstr2': [],
            'bitstr2_ops': [],
            'blitter': [],
            'blitter_ops': []
            }
    while True:
        line = fd.readline()
        if not line:
            break
        line.strip()
        if line[0] == "#":
            continue
        data = line.split()
        # TODO: detect column names from headers
        results['time'].append(float(data[0]))
        results['utime'].append(float(data[1]))
        results['stime'].append(float(data[2]))
        results['power'].append(float(data[3]))
        results['render'].append(float(data[4]))
        results['render_ops'].append(int(data[5]))
        results['bitstr'].append(float(data[6]))
        results['bitstr_ops'].append(int(data[7]))
        results['bitstr2'].append(float(data[8]))
        results['bitstr2_ops'].append(int(data[9]))
        results['blitter'].append(float(data[10]))
        results['blitter_ops'].append(int(data[11]))
    return results

def analyse(results, title, out_dir, 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'),
            ('bitstr', 'Bitstream engine usage % of GPU'),
            ('bitstr_ops', 'Bitstream engine ops per interval'),
            ('bitstr2', 'Bitstream 6 engine usage % of GPU'),
            ('bitstr2_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,
                }

    # graphics
    fig = pylab.figure()
    ax = pylab.subplot(111)
    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", "bitstr", "bitstr2", "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')

    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_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", "bitstr_ops", "bitstr2_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)")

    pylab.plot(results['power'], label="Power")
    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", "bitstr", "bitstr2", "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.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])
    ax.legend(loc = 'upper center', ncol=num_axis, fancybox=True, shadow=True, bbox_to_anchor = (0.5, -0.1))
    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", "bitstr", "bitstr2", "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.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=2, fancybox=True, shadow=True, bbox_to_anchor = (0.5, -0.1))
        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

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

You need to specify either a log file to analyse, or a command to profile.
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:', ['help', 'logfile=', 'command=', 'title=', 'output='])
    except getopt.error:
        usage(sys.argv[0])
        sys.exit(1)
    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] == '-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:
        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
    results = collect(logfile)
    analyse(results, title, output)