/
profile-analyze.py
executable file
·562 lines (476 loc) · 18.7 KB
/
profile-analyze.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
#!/usr/bin/python
"""
This script reads in the profile-raw file generated by Glulxe profiling,
and lists the ten most costly functions. (In terms of how much total time
was spent inside each function. If a function calls other functions, the
time spent in them is not charged to the parent; that is, a function
which does nothing but call other functions will be considered uncostly.)
Optionally, this script can also read the debug output of the Inform 6
compiler (or the assembly output), and use that to figure out the
names of all the functions that were profiled.
You can also generate profiling output in the same form as dumbfrotz's
Z-machine profiling output. (If that happens to be what you want.) Use
the --dumbfrotz argument.
Using this script is currently a nuisance. The requirements:
- You must compile Glulxe with profiling (the VM_PROFILING compile-time
option).
- (If you want function names) you should compile your Inform 6 source
using the -k switch. This generates a "gameinfo.dbg" file.
- Run Glulxe, using the "--profile profile-raw" option. Play some of
the game, and quit. This generates a data file called "profile-raw".
- Run this script, giving gameinfo.dbg and profile-raw as arguments.
(You can provide dispatch_dump.xml as an optional third argument.
This file gives the names of Glk functions; it is available from
https://github.com/erkyrath/glk-dev/tree/master/dispatch_dump .)
To sum up, in command-line form:
% inform -G -k game.inf
% glulxe --profile profile-raw game.ulx
% python profile-analyze.py profile-raw gameinfo.dbg dispatch_dump.xml
You can also use the assembly output of the Inform compiler, which you
get with the -a switch. Save the output and use it instead of the debug
file:
% inform -G -a game.inf > game.asm
% glulxe --profile profile-raw game.ulx
% python profile-analyze.py profile-raw game.asm dispatch_dump.xml
The limitations:
The profiling code is not smart about VM operations that rearrange the
call stack. In fact, it's downright stupid. @restart, @restore,
@restoreundo, or @throw will kill the interpreter.
Inform's -k switch does not work correctly with game files larger than
16 megabytes.
Inform's -a switch does not display code for veneer functions, so if
you use that data, these will not be named; they will be listed as
"<???>". This is a particular nuisance because veneer functions are
often the most costly ones. (Therefore, you'll almost certainly want
to use -k.)
If you leave off the "dispatch_dump.xml" argument, everything will
still work, but @glk function entries will be listed by number rather
than by name.
You can explore the profiling data in more detail by running the script
interactively:
% python -i profile-analyze.py profile-raw game.asm dispatch_dump.xml
After it runs, you'll be left at a Python prompt. The environment
will contain mappings called "functions" (mapping addresses to
function objects), and "function_names" (names to function objects).
>>> functions[0x3c]
<Function $3c 'Main__'>
>>> function_names['Main__']
<Function $3c 'Main__'>
>>> function_names['Main__'].dump()
Main__:
at $00003c (line 0); called 1 times
0.000067 sec (1 ops) spent executing
6.273244 sec (117578 ops) including child calls
A Function object has lots of attributes:
addr=INT: The VM address of the function (in hex).
hexaddr=STRING: The VM address of the function in hex (as a string).
name=STRING: The function's name, or '<???>' if the function is
not known (veneer functions).
linenum=INT: The line number of the function from the source code,
or 0 if it is not derived from source (Main__, etc).
call_count=INT: The number of times the function was called.
accel_count=INT: The number of times the function was called with
acceleration.
total_time=FLOAT: The amount of time spent during all calls to the
function (in seconds, as a floating-point value).
total_ops=INT: The number of opcodes executed during all calls to
the function.
self_time=FLOAT: The amount of time spent during all calls to the
function, excluding time spent in subcalls (functions called *by* the
function).
self_ops=INT: The number of opcodes executed during all calls to
the function, excluding time spent in subcalls.
max_depth=INT: The deepest this function has been nested on the
stack, during any call.
max_stack_use=INT: The greatest number of words on the stack, during
any call. (This is measured when the function returns, so it may
not capture the peak stack usage. If a function never returns, e.g.
Main__(), then this value is approximate.)
(The self_time is the "cost" used for the original listing.)
Note that if a function does not make any function calls, total_time
will be the same as self_time (and total_ops the same as self_ops).
Some of the function entries refer to special interpreter operations.
(These have high addresses, outside the range of normal game files.)
Functions with addresses in the 0xE0000000 range are the interpreter's
output opcodes: @streamchar, @streamunichar, @streamnum, @streamstr.
Functions with addresses in the 0xF0000000 range are @glk opcode calls.
The number in the lower bits specifies which Glk function was called.
You will always see a large self_time for function 0xF00000C0; this
represents all the time spent waiting for input in glk_select().
(Both the 0xE0000000 and 0xF0000000 entries represent time spent in the
Glk library, but they get there by different code paths.)
The function with the lowest address is the top-level Main__()
function generated by the compiler. Its total_time is the running time
of the entire program; its total_ops is the number of opcodes executed
by the entire program; its max_depth is zero.
"""
import sys, os.path
import xml.sax
from struct import unpack
dumb_frotz_mode = False
if ('--dumbfrotz' in sys.argv):
sys.argv.remove('--dumbfrotz')
dumb_frotz_mode = True
if (len(sys.argv) < 2):
print "Usage: profile-analyze.py [--dumbfrotz] profile-raw [ gameinfo.dbg | game.asm ] [ dispatch_dump.xml ]"
sys.exit(1)
profile_raw = sys.argv[1]
if (not os.path.exists(profile_raw)):
print 'File not readable:', profile_raw
sys.exit(1)
game_asm = None
if (len(sys.argv) >= 3):
game_asm = sys.argv[2]
if (not os.path.exists(game_asm)):
print 'File not readable:', game_asm
sys.exit(1)
dispatch_dump = None
if (len(sys.argv) >= 4):
dispatch_dump = sys.argv[3]
if (not os.path.exists(dispatch_dump)):
print 'File not readable:', dispatch_dump
sys.exit(1)
special_functions = {
0xE0000001: 'streamchar',
0xE0000002: 'streamunichar',
0xE0000003: 'streamnum',
0xE0000004: 'streamstr',
}
glk_functions = {}
functions = None
sourcemap = None
class Function:
def __init__(self, addr, hexaddr, attrs):
self.addr = addr
self.hexaddr = hexaddr
val = special_functions.get(addr)
if (addr >= 0xF0000000):
name = glk_functions.get(addr-0xF0000000)
if (not name):
name = hex(addr-0xF0000000)[2:]
name = '$' + name.replace('L', '')
self.name = '<@glk_' + name + '>'
self.special = True
elif (val is None):
self.name = '<???>'
self.special = False
else:
self.name = '<@' + val + '>'
self.special = True
self.linenum = 0
self.call_count = int(attrs['call_count'])
self.accel_count = 0
if (attrs.has_key('accel_count')):
self.accel_count = int(attrs['accel_count'])
self.total_ops = int(attrs['total_ops'])
self.total_time = float(attrs['total_time'])
self.self_ops = int(attrs['self_ops'])
self.self_time = float(attrs['self_time'])
if (attrs.has_key('max_depth')):
self.max_depth = int(attrs['max_depth'])
if (attrs.has_key('max_stack_use')):
self.max_stack_use = int(attrs['max_stack_use'])
def __repr__(self):
return '<Function $' + self.hexaddr + ' ' + repr(self.name) + '>'
def dump(self):
print '%s:' % (self.name,)
val = ''
if (self.accel_count):
val = ' (%d accelerated)' % (self.accel_count,)
print ' at $%06x (line %d); called %d times%s' % (self.addr, self.linenum,self.call_count,val)
print ' %.6f sec (%d ops) spent executing' % (self.self_time, self.self_ops)
print ' %.6f sec (%d ops) including child calls' % (self.total_time, self.total_ops)
def dump_dumbfrotz_style(self):
percent1 = ' '
percent2 = ' '
pc1 = int(100*(float(self.self_ops)/float(ops_executed)))
pc2 = int(100*(float(self.total_ops)/float(ops_executed)))
if (pc1 > 0):
percent1 = "%3d%%" % pc1
if (pc2 > 0):
percent2 = "%3d%%" % pc2
print '%-36s %s %-10lu %s %-10lu %-10lu %-4d' % (self.name, percent1, self.self_ops, percent2, self.total_ops, self.call_count, self.max_depth)
class DispatchDumpHandler(xml.sax.handler.ContentHandler):
def startElement(self, name, attrs):
if (name == 'function'):
addr = int(attrs['id'])
glk_functions[addr] = str(attrs['name'])
class ProfileRawHandler(xml.sax.handler.ContentHandler):
def startElement(self, name, attrs):
global functions
if (name == 'profile'):
functions = {}
if (name == 'function'):
hexaddr = attrs.get('addr')
addr = int(hexaddr, 16)
func = Function(addr, hexaddr, attrs)
functions[addr] = func
def parse_asm(fl):
global sourcemap
sourcemap = {}
lasttup = None
while True:
ln = fl.readline()
if (not ln):
break
ln = ln.strip()
ls = ln.split()
if (lasttup and not ls):
(linenum, funcname, addr) = lasttup
sourcemap[addr] = (linenum, funcname)
lasttup = None
try:
if (len(ls) >= 4 and ls[2] == '[' and ls[1].startswith('+')):
linenum = int(ls[0])
funcname = ls[3]
addr = int(ls[1][1:], 16)
lasttup = (linenum, funcname, addr)
except ValueError:
pass
class InformFunc:
def __init__(self, funcnum):
self.funcnum = funcnum
self.name = '<???>'
self.addr = 0
self.linenum = None
self.endaddr = None
self.endlinenum = None
self.locals = None
self.seqpts = None
def __repr__(self):
return '<InformFunc $' + hex(self.addr)[2:] + ' ' + repr(self.name) + '>'
class DebugFile:
def __init__(self, fl):
self.files = {}
self.functions = {}
self.function_names = {}
self.classes = []
self.objects = {}
self.arrays = {}
self.globals = {}
self.properties = {}
self.attributes = {}
self.actions = {}
self.fake_actions = {}
self.map = {}
self.header = None
dat = fl.read(2)
val = unpack('>H', dat)[0]
if (val != 0xDEBF):
raise ValueError('not an Inform debug file')
dat = fl.read(2)
self.debugversion = unpack('>H', dat)[0]
dat = fl.read(2)
self.informversion = unpack('>H', dat)[0]
rectable = {
1: self.read_file_rec,
2: self.read_class_rec,
3: self.read_object_rec,
4: self.read_global_rec,
5: self.read_attr_rec,
6: self.read_prop_rec,
7: self.read_fake_action_rec,
8: self.read_action_rec,
9: self.read_header_rec,
10: self.read_lineref_rec,
11: self.read_routine_rec,
12: self.read_array_rec,
13: self.read_map_rec,
14: self.read_routine_end_rec,
}
while True:
dat = fl.read(1)
rectype = unpack('>B', dat)[0]
if (rectype == 0):
break
recfunc = rectable.get(rectype)
if (not recfunc):
raise ValueError('unknown debug record type: %d' % (rectype,))
recfunc(fl)
for func in self.functions.values():
self.function_names[func.name] = func
def read_file_rec(self, fl):
dat = fl.read(1)
filenum = unpack('>B', dat)[0]
includename = self.read_string(fl)
realname = self.read_string(fl)
self.files[filenum] = ( includename, realname )
def read_class_rec(self, fl):
name = self.read_string(fl)
start = self.read_linenum(fl)
end = self.read_linenum(fl)
self.classes.append( (name, start, end) )
def read_object_rec(self, fl):
dat = fl.read(2)
num = unpack('>H', dat)[0]
name = self.read_string(fl)
start = self.read_linenum(fl)
end = self.read_linenum(fl)
self.objects[num] = (name, start, end)
def read_global_rec(self, fl):
dat = fl.read(1)
num = unpack('>B', dat)[0]
name = self.read_string(fl)
self.globals[num] = name
def read_array_rec(self, fl):
dat = fl.read(2)
num = unpack('>H', dat)[0]
name = self.read_string(fl)
self.arrays[num] = name
def read_attr_rec(self, fl):
dat = fl.read(2)
num = unpack('>H', dat)[0]
name = self.read_string(fl)
self.attributes[num] = name
def read_prop_rec(self, fl):
dat = fl.read(2)
num = unpack('>H', dat)[0]
name = self.read_string(fl)
self.properties[num] = name
def read_action_rec(self, fl):
dat = fl.read(2)
num = unpack('>H', dat)[0]
name = self.read_string(fl)
self.actions[num] = name
def read_fake_action_rec(self, fl):
dat = fl.read(2)
num = unpack('>H', dat)[0]
name = self.read_string(fl)
self.fake_actions[num] = name
def read_routine_rec(self, fl):
dat = fl.read(2)
funcnum = unpack('>H', dat)[0]
func = self.get_function(funcnum)
func.linenum = self.read_linenum(fl)
dat = fl.read(3)
addr = unpack('>I', '\0'+dat)[0]
func.addr = int(addr)
func.name = self.read_string(fl)
locals = []
while True:
val = self.read_string(fl)
if (not val):
break
locals.append(val)
func.locals = locals
def read_lineref_rec(self, fl):
dat = fl.read(2)
funcnum = unpack('>H', dat)[0]
func = self.get_function(funcnum)
if (not func.seqpts):
func.seqpts = []
dat = fl.read(2)
count = unpack('>H', dat)[0]
for ix in range(count):
linenum = self.read_linenum(fl)
dat = fl.read(2)
addr = unpack('>H', dat)[0]
func.seqpts.append( (linenum, addr) )
def read_routine_end_rec(self, fl):
dat = fl.read(2)
funcnum = unpack('>H', dat)[0]
func = self.get_function(funcnum)
func.endlinenum = self.read_linenum(fl)
dat = fl.read(3)
addr = unpack('>I', '\0'+dat)[0]
func.endaddr = int(addr)
def read_header_rec(self, fl):
dat = fl.read(64)
self.header = dat
def read_map_rec(self, fl):
while True:
name = self.read_string(fl)
if (not name):
break
dat = fl.read(3)
addr = unpack('>I', '\0'+dat)[0]
addr = int(addr)
self.map[name] = addr
def read_linenum(self, fl):
dat = fl.read(4)
(funcnum, linenum, charnum) = unpack('>BHB', dat)
return (funcnum, linenum, charnum)
def read_string(self, fl):
val = ''
while True:
dat = fl.read(1)
if (dat == '\0'):
return val
val += dat
def get_function(self, funcnum):
func = self.functions.get(funcnum)
if (not func):
func = InformFunc(funcnum)
self.functions[funcnum] = func
return func
# Begin the work
if (dispatch_dump):
xml.sax.parse(dispatch_dump, DispatchDumpHandler())
xml.sax.parse(profile_raw, ProfileRawHandler())
source_start = min([ func.addr for func in functions.values()
if not func.special ])
if (not dumb_frotz_mode):
print 'Code segment begins at', hex(source_start)
print len(functions), 'called functions found in', profile_raw
if (game_asm):
fl = open(game_asm, 'rb')
val = fl.read(2)
fl.close()
if (not val):
pass
elif (val == '\xde\xbf'):
fl = open(game_asm, 'rb')
debugfile = DebugFile(fl)
fl.close()
sourcemap = {}
for func in debugfile.functions.values():
sourcemap[func.addr] = ( func.linenum[1], func.name)
else:
fl = open(game_asm, 'rU')
parse_asm(fl)
fl.close()
if (sourcemap):
badls = []
for (addr, func) in functions.items():
if (func.special):
continue
tup = sourcemap.get(addr-source_start)
if (not tup):
badls.append(addr)
continue
(linenum, funcname) = tup
func.name = funcname
func.linenum = linenum
if (not dumb_frotz_mode):
if (badls):
print len(badls), 'functions from', profile_raw, 'did not appear in asm (veneer functions)'
function_names = {}
for func in functions.values():
function_names[func.name] = func
if (sourcemap):
uncalled_funcs = [ funcname for (addr, (linenum, funcname)) in sourcemap.items() if (addr+source_start) not in functions ]
if (not dumb_frotz_mode):
print len(uncalled_funcs), 'functions found in', game_asm, 'were never called'
if (dumb_frotz_mode):
ls = functions.values()
ls.sort(lambda x1, x2: cmp(x2.total_ops, x1.total_ops))
ops_executed = 0
routine_calls = 0
max_stack_use = max([func.max_stack_use for func in ls])
for func in ls:
if (func.total_ops > ops_executed):
ops_executed = func.total_ops
routine_calls = routine_calls + func.call_count
print 'Total opcodes: %lu' % ops_executed
print 'Total routine calls: %lu' % routine_calls
print 'Max. stack usage: %li' % max_stack_use
print ''
print '%-35s %-10s %-10s %-10s %-4s' % ('Routine', 'Ops', 'Ops(+Subs)', 'Calls', 'Nest')
for func in ls:
func.dump_dumbfrotz_style()
else:
print 'Functions that consumed the most time (excluding children):'
ls = functions.values()
ls.sort(lambda x1, x2: cmp(x2.self_time, x1.self_time))
for func in ls[:10]:
func.dump()