Debian Codegraph @

tools/profiling/microbenchmarks/bm_diff/bm_diff.py

raw
1 #!/usr/bin/env python3
2 #
3 # Copyright 2017 gRPC authors.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16 """ Computes the diff between two bm runs and outputs significant results """
17
18 import argparse
19 import collections
20 import json
21 import os
22 import subprocess
23 import sys
24
25 sys.path.append(os.path.join(os.path.dirname(sys.argv[0]), '..'))
26
27 import bm_constants
28 import bm_json
29 import bm_speedup
30 import tabulate
31
32 verbose = False
33
34
35 def _median(ary):
36 assert (len(ary))
37 ary = sorted(ary)
38 n = len(ary)
39 if n % 2 == 0:
40 return (ary[(n - 1) // 2] + ary[(n - 1) // 2 + 1]) / 2.0
41 else:
42 return ary[n // 2]
43
44
45 def _args():
46 argp = argparse.ArgumentParser(
47 description='Perform diff on microbenchmarks')
48 argp.add_argument('-t',
49 '--track',
50 choices=sorted(bm_constants._INTERESTING),
51 nargs='+',
52 default=sorted(bm_constants._INTERESTING),
53 help='Which metrics to track')
54 argp.add_argument('-b',
55 '--benchmarks',
56 nargs='+',
57 choices=bm_constants._AVAILABLE_BENCHMARK_TESTS,
58 default=bm_constants._AVAILABLE_BENCHMARK_TESTS,
59 help='Which benchmarks to run')
60 argp.add_argument(
61 '-l',
62 '--loops',
63 type=int,
64 default=20,
65 help=
66 'Number of times to loops the benchmarks. Must match what was passed to bm_run.py'
67 )
68 argp.add_argument('-r',
69 '--regex',
70 type=str,
71 default="",
72 help='Regex to filter benchmarks run')
73 argp.add_argument('-n', '--new', type=str, help='New benchmark name')
74 argp.add_argument('-o', '--old', type=str, help='Old benchmark name')
75 argp.add_argument('-v',
76 '--verbose',
77 type=bool,
78 help='Print details of before/after')
79 args = argp.parse_args()
80 global verbose
81 if args.verbose:
82 verbose = True
83 assert args.new
84 assert args.old
85 return args
86
87
88 def _maybe_print(str):
89 if verbose:
90 print(str)
91
92
93 class Benchmark:
94
95 def __init__(self):
96 self.samples = {
97 True: collections.defaultdict(list),
98 False: collections.defaultdict(list)
99 }
100 self.final = {}
101 self.speedup = {}
102
103 def add_sample(self, track, data, new):
104 for f in track:
105 if f in data:
106 self.samples[new][f].append(float(data[f]))
107
108 def process(self, track, new_name, old_name):
109 for f in sorted(track):
110 new = self.samples[True][f]
111 old = self.samples[False][f]
112 if not new or not old:
113 continue
114 mdn_diff = abs(_median(new) - _median(old))
115 _maybe_print('%s: %s=%r %s=%r mdn_diff=%r' %
116 (f, new_name, new, old_name, old, mdn_diff))
117 s = bm_speedup.speedup(new, old, 1e-5)
118 self.speedup[f] = s
119 if abs(s) > 3:
120 if mdn_diff > 0.5:
121 self.final[f] = '%+d%%' % s
122 return self.final.keys()
123
124 def skip(self):
125 return not self.final
126
127 def row(self, flds):
128 return [self.final[f] if f in self.final else '' for f in flds]
129
130 def speedup(self, name):
131 if name in self.speedup:
132 return self.speedup[name]
133 return None
134
135
136 def _read_json(filename, badjson_files, nonexistant_files):
137 stripped = ".".join(filename.split(".")[:-2])
138 try:
139 with open(filename) as f:
140 r = f.read()
141 return json.loads(r)
142 except IOError as e:
143 if stripped in nonexistant_files:
144 nonexistant_files[stripped] += 1
145 else:
146 nonexistant_files[stripped] = 1
147 return None
148 except ValueError as e:
149 print(r)
150 if stripped in badjson_files:
151 badjson_files[stripped] += 1
152 else:
153 badjson_files[stripped] = 1
154 return None
155
156
157 def fmt_dict(d):
158 return ''.join([" " + k + ": " + str(d[k]) + "\n" for k in d])
159
160
161 def diff(bms, loops, regex, track, old, new):
162 benchmarks = collections.defaultdict(Benchmark)
163
164 badjson_files = {}
165 nonexistant_files = {}
166 for bm in bms:
167 for loop in range(0, loops):
168 for line in subprocess.check_output([
169 'bm_diff_%s/opt/%s' % (old, bm), '--benchmark_list_tests',
170 '--benchmark_filter=%s' % regex
171 ]).splitlines():
172 line = line.decode('UTF-8')
173 stripped_line = line.strip().replace("/", "_").replace(
174 "<", "_").replace(">", "_").replace(", ", "_")
175 js_new_opt = _read_json(
176 '%s.%s.opt.%s.%d.json' % (bm, stripped_line, new, loop),
177 badjson_files, nonexistant_files)
178 js_old_opt = _read_json(
179 '%s.%s.opt.%s.%d.json' % (bm, stripped_line, old, loop),
180 badjson_files, nonexistant_files)
181 for row in bm_json.expand_json(js_new_opt):
182 name = row['cpp_name']
183 if name.endswith('_mean') or name.endswith('_stddev'):
184 continue
185 benchmarks[name].add_sample(track, row, True)
186 for row in bm_json.expand_json(js_old_opt):
187 name = row['cpp_name']
188 if name.endswith('_mean') or name.endswith('_stddev'):
189 continue
190 benchmarks[name].add_sample(track, row, False)
191
192 really_interesting = set()
193 for name, bm in benchmarks.items():
194 _maybe_print(name)
195 really_interesting.update(bm.process(track, new, old))
196 fields = [f for f in track if f in really_interesting]
197
198 # figure out the significance of the changes... right now we take the 95%-ile
199 # benchmark delta %-age, and then apply some hand chosen thresholds
200 histogram = []
201 _NOISY = ["BM_WellFlushed"]
202 for name, bm in benchmarks.items():
203 if name in _NOISY:
204 print("skipping noisy benchmark '%s' for labelling evaluation" %
205 name)
206 if bm.skip():
207 continue
208 d = bm.speedup['cpu_time']
209 if d is None:
210 continue
211 histogram.append(d)
212 histogram.sort()
213 print("histogram of speedups: ", histogram)
214 if len(histogram) == 0:
215 significance = 0
216 else:
217 delta = histogram[int(len(histogram) * 0.95)]
218 mul = 1
219 if delta < 0:
220 delta = -delta
221 mul = -1
222 if delta < 2:
223 significance = 0
224 elif delta < 5:
225 significance = 1
226 elif delta < 10:
227 significance = 2
228 else:
229 significance = 3
230 significance *= mul
231
232 headers = ['Benchmark'] + fields
233 rows = []
234 for name in sorted(benchmarks.keys()):
235 if benchmarks[name].skip():
236 continue
237 rows.append([name] + benchmarks[name].row(fields))
238 note = None
239 if len(badjson_files):
240 note = 'Corrupt JSON data (indicates timeout or crash): \n%s' % fmt_dict(
241 badjson_files)
242 if len(nonexistant_files):
243 if note:
244 note += '\n\nMissing files (indicates new benchmark): \n%s' % fmt_dict(
245 nonexistant_files)
246 else:
247 note = '\n\nMissing files (indicates new benchmark): \n%s' % fmt_dict(
248 nonexistant_files)
249 if rows:
250 return tabulate.tabulate(rows, headers=headers,
251 floatfmt='+.2f'), note, significance
252 else:
253 return None, note, 0
254
255
256 if __name__ == '__main__':
257 args = _args()
258 diff, note = diff(args.benchmarks, args.loops, args.regex, args.track,
259 args.old, args.new, args.counters)
260 print('%s\n%s' % (note, diff if diff else "No performance differences"))