Debian Codegraph @

tools/TimeFileMaker.py

raw symbols SCIP
1 from __future__ import with_statement
2 from __future__ import division
3 from __future__ import unicode_literals
4 from __future__ import print_function
5 import sys
6 import re
7 import argparse
8 import os
9 import math
10 from io import open
11
12 # This script parses the output of `make TIMED=1` into a dictionary
13 # mapping names of compiled files to the number of minutes and seconds
14 # that they took to compile.
15
16 STRIP_REG = re.compile('^(?:%s/)?(coq/|contrib/|)(?:theories/|src/)?' % re.escape(os.getcwd()))
17 STRIP_REP = r'\1'
18 INFINITY = '\u221e'
19
20 TIME_KEY = 'time'
21 MEM_KEY = 'mem'
22
23 def nonnegative(arg):
24 v = int(arg)
25 if v < 0: raise argparse.ArgumentTypeError("%s is an invalid non-negative int value" % arg)
26 return v
27
28 def add_sort_by(parser):
29 return parser.add_argument(
30 '--sort-by', type=str, dest='sort_by', choices=('auto', 'absolute', 'diff'),
31 default='auto',
32 help=('How to sort the table entries.\n' +
33 'The "auto" method sorts by absolute time differences ' +
34 'rounded towards zero to a whole-number of seconds, then ' +
35 'by times in the "after" column, and finally ' +
36 'lexicographically by file name. This will put the ' +
37 'biggest changes in either direction first, and will ' +
38 'prefer sorting by build-time over subsecond changes in ' +
39 'build time (which are frequently noise); lexicographic ' +
40 'sorting forces an order on files which take effectively ' +
41 'no time to compile.\n' +
42 'The "absolute" method sorts by the total time taken.\n' +
43 'The "diff" method sorts by the signed difference in time.'))
44
45 def add_sort_by_mem(parser):
46 return parser.add_argument(
47 '--sort-by-mem', action='store_true', dest='sort_by_mem',
48 help=('Sort the table entries by memory rather than time.'))
49
50 def add_fuzz(parser):
51 return parser.add_argument(
52 '--fuzz', dest='fuzz', metavar='N', type=nonnegative, default=0,
53 help=('By default, two lines are only considered the same if ' +
54 'the character offsets and initial code strings match. '
55 'This option relaxes this constraint by allowing the ' +
56 'character offsets to differ by up to N characters, as long ' +
57 'as the total number of characters and initial code strings ' +
58 'continue to match. This is useful when there are small changes ' +
59 'to a file, and you want to match later lines that have not ' +
60 'changed even though the character offsets have changed.'))
61
62 def add_real(parser, single_timing=False):
63 return parser.add_argument(
64 '--real', action='store_true',
65 help=(r'''Use real times rather than user times.
66
67 ''' + ('''By default, the input is expected to contain lines in the format:
68 FILE_NAME (...user: NUMBER_IN_SECONDS...mem: NUMBER ko...)
69 If --real is passed, then the lines are instead expected in the format:
70 FILE_NAME (...real: NUMBER_IN_SECONDS...mem: NUMBER ko...)''' if not single_timing else
71 '''The input is expected to contain lines in the format:
72 Chars START - END COMMAND NUMBER secs (NUMBERu...)''')))
73
74 def add_user(parser, single_timing=False):
75 return parser.add_argument(
76 '--user', dest='real', action='store_false',
77 help=(r'''Use user times rather than real times.
78
79 ''' + ('''By default, the input is expected to contain lines in the format:
80 FILE_NAME (...real: NUMBER_IN_SECONDS...mem: NUMBER ko...)
81 If --user is passed, then the lines are instead expected in the format:
82 FILE_NAME (...user: NUMBER_IN_SECONDS...mem: NUMBER ko...)''' if not single_timing else
83 '''The input is expected to contain lines in the format:
84 Chars START - END COMMAND NUMBER secs (NUMBERu...)''')))
85
86 def add_include_mem(parser):
87 return parser.add_argument(
88 '--no-include-mem', dest='include_mem', default=True, action='store_false',
89 help=(r'''Don't include memory in the table.'''))
90
91 # N.B. We need to include default=None for nargs='*', c.f., https://bugs.python.org/issue28609#msg280180
92 def add_file_name_gen(parser, prefix='', descr='file containing the build log', stddir='in', defaults=None, **kwargs):
93 extra = ('' if defaults is None else ' (defaults to %s if no argument is passed)' % defaults)
94 return parser.add_argument(
95 prefix + 'FILE_NAME', type=str,
96 help=('The name of the %s (use "-" for std%s)%s.' % (descr, stddir, extra)),
97 **kwargs)
98
99 def add_file_name(parser): return add_file_name_gen(parser)
100 def add_after_file_name(parser): return add_file_name_gen(parser, 'AFTER_', 'file containing the "after" build log')
101 def add_before_file_name(parser): return add_file_name_gen(parser, 'BEFORE_', 'file containing the "before" build log')
102 def add_output_file_name(parser): return add_file_name_gen(parser, 'OUTPUT_', 'file to write the output table to', stddir='out', defaults='-', nargs='*', default=None)
103
104
105 def reformat_time_string(time):
106 try:
107 seconds, milliseconds = time.split('.')
108 except ValueError:
109 print('WARNING: Invalid time string: not the right number of dots (.); expected one: %s' % repr(time), file=sys.stderr)
110 seconds, milliseconds = (time + '.').split('.')[:2]
111 if seconds == '': seconds = 0
112 seconds = int(seconds)
113 minutes, seconds = divmod(seconds, 60)
114 return '%dm%02d.%ss' % (minutes, seconds, milliseconds)
115
116 def get_file_lines(file_name):
117 if file_name == '-':
118 if hasattr(sys.stdin, 'buffer'):
119 lines = sys.stdin.buffer.readlines()
120 else:
121 lines = sys.stdin.readlines()
122 else:
123 with open(file_name, 'rb') as f:
124 lines = f.readlines()
125 for line in lines:
126 try:
127 # Since we read the files in binary mode, we have to
128 # normalize Windows line endings from \r\n to \n
129 yield line.decode('utf-8').replace('\r\n', '\n')
130 except UnicodeDecodeError: # invalid utf-8
131 pass
132
133 def get_file(file_name):
134 return ''.join(get_file_lines(file_name))
135
136 def merge_dicts(d1, d2):
137 if d2 is None: return d1
138 if d1 is None: return d2
139 assert(isinstance(d1, dict))
140 assert(isinstance(d2, dict))
141 ret = {}
142 for k in set(list(d1.keys()) + list(d2.keys())):
143 ret[k] = merge_dicts(d1.get(k), d2.get(k))
144 return ret
145
146 def get_mems_of_lines(lines):
147 reg = re.compile(r'^([^\s]+) \([^\)]*?mem: ([0-9]+) ko[^\)]*?\)\s*$', re.MULTILINE)
148 mems = reg.findall(lines)
149 if all(STRIP_REG.search(name.strip()) for name, mem in mems):
150 mems = tuple((STRIP_REG.sub(STRIP_REP, name.strip()), mem) for name, mem in mems)
151 return dict((name, {MEM_KEY:int(mem)}) for name, mem in mems)
152
153 def get_times_of_lines(lines, use_real=False):
154 reg_user = re.compile(r'^([^\s]+) \([^\)]*?user: ([0-9\.]+)[^\)]*?\)\s*$', re.MULTILINE)
155 reg_real = re.compile(r'^([^\s]+) \([^\)]*?real: ([0-9\.]+)[^\)]*?\)\s*$', re.MULTILINE)
156 reg = reg_real if use_real else reg_user
157 times = reg.findall(lines)
158 if all(time in ('0.00', '0.01') for name, time in times):
159 reg = reg_real
160 times = reg.findall(lines)
161 if all(STRIP_REG.search(name.strip()) for name, time in times):
162 times = tuple((STRIP_REG.sub(STRIP_REP, name.strip()), time) for name, time in times)
163 return dict((name, {TIME_KEY:reformat_time_string(time)}) for name, time in times)
164
165 def get_times_and_mems(file_name, use_real=False, include_mem=True):
166 # we only get the file once, in case it is a stream like stdin
167 lines = get_file(file_name)
168 return merge_dicts(get_times_of_lines(lines, use_real=use_real),
169 (get_mems_of_lines(lines) if include_mem else None))
170
171 def get_mems(file_name):
172 '''
173 Reads the contents of file_name, which should be the output of
174 'make TIMED=1', and parses it to construct a dict mapping file
175 names to peak memory usage, as integers. Removes common prefixes
176 using STRIP_REG and STRIP_REP.
177 '''
178 return get_mems_of_lines(get_file(file_name))
179
180 def get_times(file_name, use_real=False):
181 '''
182 Reads the contents of file_name, which should be the output of
183 'make TIMED=1', and parses it to construct a dict mapping file
184 names to compile durations, as strings. Removes common prefixes
185 using STRIP_REG and STRIP_REP.
186 '''
187 return get_times_of_lines(get_file(file_name))
188
189 def get_single_file_times(file_name, use_real=False):
190 '''
191 Reads the contents of file_name, which should be the output of
192 'coqc -time', and parses it to construct a dict mapping lines to
193 to compile durations, as strings.
194 '''
195 lines = get_file(file_name)
196 reg = re.compile(r'^Chars ([0-9]+) - ([0-9]+) ([^ ]+) ([0-9\.]+) secs \(([0-9\.]+)u(.*)\)$', re.MULTILINE)
197 times = reg.findall(lines)
198 if len(times) == 0: return dict()
199 longest = max(max((len(start), len(stop))) for start, stop, name, real, user, extra in times)
200 FORMAT = 'Chars %%0%dd - %%0%dd %%s' % (longest, longest)
201 return dict((FORMAT % (int(start), int(stop), name), {TIME_KEY:reformat_time_string(real if use_real else user)}) for start, stop, name, real, user, extra in times)
202
203 def fuzz_merge(l1, l2, fuzz):
204 '''Takes two iterables of ((start, end, code), times) and a fuzz
205 parameter, and yields a single iterable of ((start, stop, code),
206 times1, times2)
207
208 We only give both left and right if (a) the codes are the same,
209 (b) the number of characters (stop - start) is the same, and (c)
210 the difference between left and right code locations is <= fuzz.
211
212 We keep a current guess at the overall offset, and prefer drawing
213 from whichever list is earliest after correcting for current
214 offset.
215
216 '''
217 assert(fuzz >= 0)
218 cur_fuzz = 0
219 l1 = list(l1)
220 l2 = list(l2)
221 cur1, cur2 = None, None
222 while (len(l1) > 0 or cur1 is not None) and (len(l2) > 0 or cur2 is not None):
223 if cur1 is None: cur1 = l1.pop(0)
224 if cur2 is None: cur2 = l2.pop(0)
225 ((s1, e1, c1), t1), ((s2, e2, c2), t2) = cur1, cur2
226 assert(t1 is not None)
227 assert(t2 is not None)
228 s2_adjusted, e2_adjusted = s2 + cur_fuzz, e2 + cur_fuzz
229 if cur1[0] == cur2[0]:
230 yield (cur1, cur2)
231 cur1, cur2 = None, None
232 cur_fuzz = 0
233 elif c1 == c2 and e1-s1 == e2-s2 and abs(s1 - s2) <= fuzz:
234 yield (((s1, e1, c1), t1), ((s2, e2, c2), t2))
235 cur1, cur2 = None, None
236 cur_fuzz = s1 - s2
237 elif s1 < s2_adjusted or (s1 == s2_adjusted and e1 <= e2):
238 yield (((s1, e1, c1), t1), ((s1 - cur_fuzz, e1 - cur_fuzz, c1), None))
239 cur1 = None
240 else:
241 yield (((s2 + cur_fuzz, e2 + cur_fuzz, c2), None), ((s2, e2, c2), t2))
242 cur2 = None
243 if len(l1) > 0:
244 for i in l1: yield (i, (i[0], None))
245 elif len(l2) > 0:
246 for i in l2: yield ((i[0], None), i)
247
248 def adjust_fuzz(left_dict, right_dict, fuzz):
249 reg = re.compile(r'Chars ([0-9]+) - ([0-9]+) (.*)$')
250 left_dict_list = sorted(((int(s), int(e), c), v) for ((s, e, c), v) in ((reg.match(k).groups(), v) for k, v in left_dict.items()))
251 right_dict_list = sorted(((int(s), int(e), c), v) for ((s, e, c), v) in ((reg.match(k).groups(), v) for k, v in right_dict.items()))
252 merged = list(fuzz_merge(left_dict_list, right_dict_list, fuzz))
253 if len(merged) == 0:
254 # assert that both left and right dicts are empty
255 assert(not left_dict)
256 assert(not right_dict)
257 return left_dict, right_dict
258 longest = max(max((len(str(start1)), len(str(stop1)), len(str(start2)), len(str(stop2)))) for ((start1, stop1, code1), t1), ((start2, stop2, code2), t2) in merged)
259 FORMAT1 = 'Chars %%0%dd - %%0%dd %%s' % (longest, longest)
260 FORMAT2 = 'Chars %%0%dd-%%0%dd ~ %%0%dd-%%0%dd %%s' % (longest, longest, longest, longest)
261 if fuzz == 0:
262 left_dict = dict((FORMAT1 % k, t1) for (k, t1), _ in merged if t1 is not None)
263 right_dict = dict((FORMAT1 % k, t2) for _, (k, t2) in merged if t2 is not None)
264 else:
265 left_dict = dict((FORMAT2 % (s1, e1, s2, e2, c1), t1) for ((s1, e1, c1), t1), ((s2, e2, c2), t2) in merged if t1 is not None)
266 right_dict = dict((FORMAT2 % (s1, e1, s2, e2, c1), t2) for ((s1, e1, c1), t1), ((s2, e2, c2), t2) in merged if t2 is not None)
267 return left_dict, right_dict
268
269 def fix_sign_for_sorting(num, descending=True):
270 return -num if descending else num
271
272 def make_sorting_key(stats_dict, descending=True, sort_by_mem=False):
273 if sort_by_mem:
274 def get_key(name):
275 if MEM_KEY not in stats_dict[name].keys():
276 print('WARNING: %s has no mem key: %s' % (name, repr(stats_dict[name])), file=sys.stderr)
277 mem = stats_dict[name].get(MEM_KEY, '0')
278 return (fix_sign_for_sorting(int(mem), descending=descending),
279 name)
280 else:
281 def get_key(name):
282 if TIME_KEY not in stats_dict[name].keys():
283 print('WARNING: %s has no time key: %s' % (name, repr(stats_dict[name])), file=sys.stderr)
284 minutes, seconds = stats_dict[name].get(TIME_KEY, '0m00s').replace('s', '').split('m')
285 return (fix_sign_for_sorting(int(minutes), descending=descending),
286 fix_sign_for_sorting(float(seconds), descending=descending),
287 name)
288 return get_key
289
290 def get_sorted_file_list_from_stats_dict(stats_dict, descending=True, sort_by_mem=False):
291 '''
292 Takes the output dict of get_times and returns the list of keys,
293 sorted by duration.
294 '''
295 return sorted(stats_dict.keys(), key=make_sorting_key(stats_dict, descending=descending, sort_by_mem=sort_by_mem))
296
297 def to_seconds(time):
298 '''
299 Converts a string time into a number of seconds.
300 '''
301 minutes, seconds = time.replace('s', '').split('m')
302 sign = -1 if time[0] == '-' else 1
303 return sign * (abs(int(minutes)) * 60 + float(seconds))
304
305 def from_seconds(seconds, signed=False):
306 '''
307 Converts a number of seconds into a string time.
308 '''
309 sign = ('-' if seconds < 0 else '+') if signed else ''
310 full_centiseconds = round(abs(seconds) * 100)
311 seconds = int(full_centiseconds) // 100
312 centiseconds = full_centiseconds - (seconds * 100)
313 minutes = int(seconds) // 60
314 seconds -= minutes * 60
315 return sign + '%dm%02d.%02ds' % (minutes, seconds, centiseconds)
316
317 def sum_times(times, signed=False):
318 '''
319 Takes the values of an output from get_times, parses the time
320 strings, and returns their sum, in the same string format.
321 '''
322 # sort the times before summing because floating point addition is not associative
323 return from_seconds(math.fsum(sorted(map(to_seconds, times))), signed=signed)
324
325 def format_percentage(num, signed=True):
326 sign = ('-' if num < 0 else '+') if signed else ''
327 num = abs(num)
328 whole_part = int(num * 100)
329 frac_part = int(100 * (num * 100 - whole_part))
330 return sign + '%d.%02d%%' % (whole_part, frac_part)
331
332 def make_diff_table_string(left_dict, right_dict,
333 sort_by='auto',
334 descending=True, sort_by_mem=False,
335 left_tag='After', tag='File Name', right_tag='Before', with_percent=True,
336 left_mem_tag='Peak Mem', right_mem_tag='Peak Mem',
337 include_mem=False,
338 change_tag='Change', percent_change_tag='% Change',
339 change_mem_tag='Change (mem)', percent_change_mem_tag='% Change (mem)',
340 mem_fmt='%d ko'):
341 # We first get the names of all of the compiled files: all files
342 # that were compiled either before or after.
343 all_names_dict = dict()
344 all_names_dict.update(right_dict)
345 all_names_dict.update(left_dict) # do the left (after) last, so that we give precedence to those ones
346 if len(all_names_dict.keys()) == 0: return 'No timing data'
347 get_time = (lambda d, name: to_seconds(d.get(name, {}).get(TIME_KEY, '0m0.0s')))
348 prediff_times = tuple((name, get_time(left_dict, name), get_time(right_dict, name))
349 for name in all_names_dict.keys())
350 diff_times_dict = dict((name, from_seconds(lseconds - rseconds, signed=True))
351 for name, lseconds, rseconds in prediff_times)
352 percent_diff_times_dict = dict((name, ((format_percentage((lseconds - rseconds) / rseconds))
353 if rseconds != 0 else (INFINITY if lseconds > 0 else 'N/A')))
354 for name, lseconds, rseconds in prediff_times)
355
356 get_mem = (lambda d, name: d.get(name, {}).get(MEM_KEY, 0))
357 prediff_mems = tuple((name, get_mem(left_dict, name), get_mem(right_dict, name))
358 for name in all_names_dict.keys())
359 diff_mems_dict = dict((name, lmem - rmem) for name, lmem, rmem in prediff_mems)
360 percent_diff_mems_dict = dict((name, ((format_percentage((lmem - rmem) / float(rmem)))
361 if rmem != 0 else (INFINITY if lmem > 0 else 'N/A')))
362 for name, lmem, rmem in prediff_mems)
363
364 # update to sort by approximate difference, first
365 if sort_by_mem:
366 get_prekey = (lambda name: diff_mems_dict[name])
367 else:
368 get_prekey = (lambda name: to_seconds(diff_times_dict[name]))
369 get_key_abs = make_sorting_key(all_names_dict, descending=descending, sort_by_mem=sort_by_mem)
370 get_key_diff_float = (lambda name: fix_sign_for_sorting(get_prekey(name), descending=descending))
371 get_key_diff_absint = (lambda name: fix_sign_for_sorting(int(abs(get_prekey(name))), descending=descending))
372 get_key_with_name = (lambda get_key: lambda name: (get_key(name), name))
373 if sort_by == 'absolute':
374 get_key = get_key_with_name(get_key_abs)
375 elif sort_by == 'diff':
376 get_key = get_key_with_name(get_key_diff_float)
377 else: # sort_by == 'auto'
378 get_key = get_key_with_name((lambda name: (get_key_diff_absint(name), get_key_abs(name))))
379 names = sorted(all_names_dict.keys(), key=get_key)
380 #names = get_sorted_file_list_from_stats_dict(all_names_dict, descending=descending)
381 # set the widths of each of the columns by the longest thing to go in that column
382 left_sum = sum_times(v[TIME_KEY] for v in left_dict.values() if TIME_KEY in v.keys())
383 right_sum = sum_times(v[TIME_KEY] for v in right_dict.values() if TIME_KEY in v.keys())
384 left_sum_float = sum(sorted(to_seconds(v[TIME_KEY]) for v in left_dict.values() if TIME_KEY in v.keys()))
385 right_sum_float = sum(sorted(to_seconds(v[TIME_KEY]) for v in right_dict.values() if TIME_KEY in v.keys()))
386 diff_sum = from_seconds(left_sum_float - right_sum_float, signed=True)
387 percent_diff_sum = (format_percentage((left_sum_float - right_sum_float) / right_sum_float)
388 if right_sum_float > 0 else 'N/A')
389
390 left_width = max(max(map(len, ['N/A', left_tag] + [v[TIME_KEY] for v in left_dict.values() if TIME_KEY in v.keys()])), len(left_sum))
391 right_width = max(max(map(len, ['N/A', right_tag] + [v[TIME_KEY] for v in right_dict.values() if TIME_KEY in v.keys()])), len(right_sum))
392 far_right_width = max(max(map(len, ['N/A', change_tag] + list(diff_times_dict.values()))), len(diff_sum))
393 far_far_right_width = max(max(map(len, ['N/A', percent_change_tag] + list(percent_diff_times_dict.values()))), len(percent_diff_sum))
394 total_string = 'Total' if not include_mem else 'Total Time / Peak Mem'
395 filenames_width = max(map(len, names + [tag, total_string]))
396
397 left_peak = max([0] + [v.get(MEM_KEY, 0) for v in left_dict.values()])
398 right_peak = max([0] + [v.get(MEM_KEY, 0) for v in right_dict.values()])
399 diff_peak = left_peak - right_peak
400 percent_diff_peak = (format_percentage((left_peak - right_peak) / float(right_peak))
401 if right_peak != 0 else (INFINITY if left_peak > 0 else 'N/A'))
402
403 left_mem_width = max(max(map(len, ['N/A', left_mem_tag] + [mem_fmt % v.get(MEM_KEY, 0) for v in left_dict.values()])), len(mem_fmt % left_peak))
404 right_mem_width = max(max(map(len, ['N/A', right_mem_tag] + [mem_fmt % v.get(MEM_KEY, 0) for v in right_dict.values()])), len(mem_fmt % right_peak))
405 far_right_mem_width = max(max(map(len, ['N/A', change_mem_tag] + [mem_fmt % v for v in diff_mems_dict.values()])), len(mem_fmt % diff_peak))
406 far_far_right_mem_width = max(max(map(len, ['N/A', percent_change_mem_tag] + list(percent_diff_mems_dict.values()))), len(percent_diff_peak))
407
408 if include_mem:
409 format_string = ("%%(left)%ds | %%(left_mem)%ds | %%(right)%ds | %%(right_mem)%ds || %%(far_right)%ds || %%(far_right_mem)%ds"
410 % (left_width, left_mem_width, right_width, right_mem_width, far_right_width, far_right_mem_width))
411 else:
412 format_string = ("%%(left)%ds | %%(right)%ds || %%(far_right)%ds"
413 % (left_width, right_width, far_right_width))
414
415 if with_percent:
416 format_string += " | %%(far_far_right)%ds" % far_far_right_width
417 if include_mem:
418 format_string += " | %%(far_far_right_mem)%ds" % far_far_right_mem_width
419
420 format_string += " | %%(filenames)-%ds" % filenames_width
421
422 header = format_string % {'left': left_tag, 'left_mem': left_mem_tag,
423 'right': right_tag, 'right_mem': right_mem_tag,
424 'far_right': change_tag, 'far_right_mem': change_mem_tag,
425 'far_far_right': percent_change_tag, 'far_far_right_mem': percent_change_mem_tag,
426 'filenames': tag}
427 total = format_string % {'left': left_sum, 'left_mem': mem_fmt % left_peak,
428 'right': right_sum, 'right_mem': mem_fmt % right_peak,
429 'far_right': diff_sum, 'far_right_mem': mem_fmt % diff_peak,
430 'far_far_right': percent_diff_sum, 'far_far_right_mem': percent_diff_peak,
431 'filenames': total_string}
432 # separator to go between headers and body
433 sep = '-' * len(header)
434 # the representation of the default value (0), to get replaced by N/A
435 left_rep, right_rep, far_right_rep, far_far_right_rep = ("%%%ds | " % left_width) % 'N/A', (" | %%%ds |" % right_width) % 'N/A', ("|| %%%ds" % far_right_width) % 'N/A', ("| %%%ds" % far_far_right_width) % 'N/A'
436 left_mem_rep, right_mem_rep, far_right_mem_rep, far_far_right_mem_rep = ("%%%ds | " % left_mem_width) % 'N/A', (" | %%%ds |" % right_mem_width) % 'N/A', ("|| %%%ds" % far_right_mem_width) % 'N/A', ("| %%%ds" % far_far_right_mem_width) % 'N/A'
437 get_formatted_mem = (lambda k, v: (mem_fmt % v[k]) if k in v.keys() else 'N/A')
438 return '\n'.join([header, sep, total, sep] +
439 [format_string % {'left': left_dict.get(name, {}).get(TIME_KEY, 'N/A'),
440 'left_mem': get_formatted_mem(MEM_KEY, left_dict.get(name, {})),
441 'right': right_dict.get(name, {}).get(TIME_KEY, 'N/A'),
442 'right_mem': get_formatted_mem(MEM_KEY, right_dict.get(name, {})),
443 'far_right': diff_times_dict.get(name, 'N/A'),
444 'far_right_mem': get_formatted_mem(name, diff_mems_dict),
445 'far_far_right': percent_diff_times_dict.get(name, 'N/A'),
446 'far_far_right_mem': percent_diff_mems_dict.get(name, 'N/A'),
447 'filenames': name}
448 for name in names]).replace(left_rep, 'N/A'.center(len(left_rep) - 3) + ' | ').replace(right_rep, ' | ' + 'N/A'.center(len(right_rep) - 5) + ' |').replace(far_right_rep, '|| ' + 'N/A'.center(len(far_right_rep) - 3)).replace(far_far_right_rep, '| ' + 'N/A'.center(len(far_far_right_rep) - 2)).replace(left_mem_rep, 'N/A'.center(len(left_mem_rep) - 3) + ' | ').replace(right_mem_rep, ' | ' + 'N/A'.center(len(right_mem_rep) - 5) + ' |').replace(far_right_mem_rep, '|| ' + 'N/A'.center(len(far_right_mem_rep) - 3)).replace(far_far_right_mem_rep, '| ' + 'N/A'.center(len(far_far_right_mem_rep) - 2))
449
450 def make_table_string(stats_dict,
451 descending=True, sort_by_mem=False,
452 tag="Time", mem_tag="Peak Mem", mem_fmt='%d ko',
453 include_mem=False):
454 if len(stats_dict.keys()) == 0: return 'No timing data'
455 # We first get the names of all of the compiled files, sorted by
456 # duration
457 names = get_sorted_file_list_from_stats_dict(stats_dict, descending=descending, sort_by_mem=sort_by_mem)
458 # compute the widths of the columns
459 times_width = max(len('N/A'), len(tag), max(len(v[TIME_KEY]) for v in stats_dict.values() if TIME_KEY in v.keys()), len(sum_times(v[TIME_KEY] for v in stats_dict.values() if TIME_KEY in v.keys())))
460 mems_width = max(len('N/A'), len(mem_tag), max(len(mem_fmt % v.get(MEM_KEY, 0)) for v in stats_dict.values()), len(mem_fmt % (max(v.get(MEM_KEY, 0) for v in stats_dict.values()))))
461 total_string = 'Total' if not include_mem else 'Total Time / Peak Mem'
462 names_width = max(map(len, names + ["File Name", total_string]))
463 if include_mem:
464 format_string = "%%(time)%ds | %%(mem)%ds | %%(name)-%ds" % (times_width, mems_width, names_width)
465 else:
466 format_string = "%%(time)%ds | %%(name)-%ds" % (times_width, names_width)
467 get_formatted_mem = (lambda k, v: (mem_fmt % v[k]) if k in v.keys() else 'N/A')
468 header = format_string % {'time': tag, 'mem': mem_tag, 'name': 'File Name'}
469 total = format_string % {'time': sum_times(v[TIME_KEY] for v in stats_dict.values() if TIME_KEY in v.keys()),
470 'mem': ((mem_fmt % max(v[MEM_KEY] for v in stats_dict.values() if MEM_KEY in v.keys())) if any(MEM_KEY in v.keys() for v in stats_dict.values()) else 'N/A'),
471 'name': total_string}
472 sep = '-' * len(header)
473 return '\n'.join([header, sep, total, sep] +
474 [format_string % {'time': stats_dict[name].get(TIME_KEY, 'N/A'),
475 'mem': get_formatted_mem(MEM_KEY, stats_dict[name]),
476 'name': name}
477 for name in names])
478
479 def print_or_write_table(table, files):
480 if table[-1] != '\n': table += '\n'
481 if len(files) == 0 or '-' in files:
482 if hasattr(sys.stdout, 'buffer'):
483 sys.stdout.buffer.write(table.encode("utf-8"))
484 else:
485 sys.stdout.write(table.encode("utf-8"))
486 for file_name in files:
487 if file_name != '-':
488 with open(file_name, 'w', encoding="utf-8") as f:
489 f.write(table)