Debian Codegraph @

contrib/revsetbenchmarks.py

raw
1 #!/usr/bin/env python3
2
3 # Measure the performance of a list of revsets against multiple revisions
4 # defined by parameter. Checkout one by one and run perfrevset with every
5 # revset in the list to benchmark its performance.
6 #
7 # You should run this from the root of your mercurial repository.
8 #
9 # call with --help for details
10
11 import math
12 import optparse # cannot use argparse, python 2.7 only
13 import os
14 import re
15 import subprocess
16 import sys
17
18 DEFAULTVARIANTS = [
19 'plain',
20 'min',
21 'max',
22 'first',
23 'last',
24 'reverse',
25 'reverse+first',
26 'reverse+last',
27 'sort',
28 'sort+first',
29 'sort+last',
30 ]
31
32
33 def check_output(*args, **kwargs):
34 kwargs.setdefault('stderr', subprocess.PIPE)
35 kwargs.setdefault('stdout', subprocess.PIPE)
36 proc = subprocess.Popen(*args, **kwargs)
37 output, error = proc.communicate()
38 if proc.returncode != 0:
39 raise subprocess.CalledProcessError(proc.returncode, ' '.join(args[0]))
40 return output
41
42
43 def update(rev):
44 """update the repo to a revision"""
45 try:
46 subprocess.check_call(['hg', 'update', '--quiet', '--check', str(rev)])
47 check_output(
48 ['make', 'local'], stderr=None
49 ) # suppress output except for error/warning
50 except subprocess.CalledProcessError as exc:
51 print('update to revision %s failed, aborting' % rev, file=sys.stderr)
52 sys.exit(exc.returncode)
53
54
55 def hg(cmd, repo=None):
56 """run a mercurial command
57
58 <cmd> is the list of command + argument,
59 <repo> is an optional repository path to run this command in."""
60 fullcmd = ['./hg']
61 if repo is not None:
62 fullcmd += ['-R', repo]
63 fullcmd += [
64 '--config',
65 'extensions.perf=' + os.path.join(contribdir, 'perf.py'),
66 ]
67 fullcmd += cmd
68 return check_output(fullcmd, stderr=subprocess.STDOUT)
69
70
71 def perf(revset, target=None, contexts=False):
72 """run benchmark for this very revset"""
73 try:
74 args = ['perfrevset']
75 if contexts:
76 args.append('--contexts')
77 args.append('--')
78 args.append(revset)
79 output = hg(args, repo=target)
80 return parseoutput(output)
81 except subprocess.CalledProcessError as exc:
82 print(
83 'abort: cannot run revset benchmark: %s' % exc.cmd, file=sys.stderr
84 )
85 if getattr(exc, 'output', None) is None: # no output before 2.7
86 print('(no output)', file=sys.stderr)
87 else:
88 print(exc.output, file=sys.stderr)
89 return None
90
91
92 outputre = re.compile(
93 br'! wall (\d+.\d+) comb (\d+.\d+) user (\d+.\d+) '
94 br'sys (\d+.\d+) \(best of (\d+)\)'
95 )
96
97
98 def parseoutput(output):
99 """parse a textual output into a dict
100
101 We cannot just use json because we want to compare with old
102 versions of Mercurial that may not support json output.
103 """
104 match = outputre.search(output)
105 if not match:
106 print('abort: invalid output:', file=sys.stderr)
107 print(output, file=sys.stderr)
108 sys.exit(1)
109 return {
110 'comb': float(match.group(2)),
111 'count': int(match.group(5)),
112 'sys': float(match.group(3)),
113 'user': float(match.group(4)),
114 'wall': float(match.group(1)),
115 }
116
117
118 def printrevision(rev):
119 """print data about a revision"""
120 sys.stdout.write("Revision ")
121 sys.stdout.flush()
122 subprocess.check_call(
123 [
124 'hg',
125 'log',
126 '--rev',
127 str(rev),
128 '--template',
129 '{if(tags, " ({tags})")} ' '{rev}:{node|short}: {desc|firstline}\n',
130 ]
131 )
132
133
134 def idxwidth(nbidx):
135 """return the max width of number used for index
136
137 This is similar to log10(nbidx), but we use custom code here
138 because we start with zero and we'd rather not deal with all the
139 extra rounding business that log10 would imply.
140 """
141 nbidx -= 1 # starts at 0
142 idxwidth = 0
143 while nbidx:
144 idxwidth += 1
145 nbidx //= 10
146 if not idxwidth:
147 idxwidth = 1
148 return idxwidth
149
150
151 def getfactor(main, other, field, sensitivity=0.05):
152 """return the relative factor between values for 'field' in main and other
153
154 Return None if the factor is insignificant (less than <sensitivity>
155 variation)."""
156 factor = 1
157 if main is not None:
158 factor = other[field] / main[field]
159 low, high = 1 - sensitivity, 1 + sensitivity
160 if low < factor < high:
161 return None
162 return factor
163
164
165 def formatfactor(factor):
166 """format a factor into a 4 char string
167
168 22%
169 156%
170 x2.4
171 x23
172 x789
173 x1e4
174 x5x7
175
176 """
177 if factor is None:
178 return ' '
179 elif factor < 2:
180 return '%3i%%' % (factor * 100)
181 elif factor < 10:
182 return 'x%3.1f' % factor
183 elif factor < 1000:
184 return '%4s' % ('x%i' % factor)
185 else:
186 order = int(math.log(factor)) + 1
187 while math.log(factor) > 1:
188 factor //= 0
189 return 'x%ix%i' % (factor, order)
190
191
192 def formattiming(value):
193 """format a value to strictly 8 char, dropping some precision if needed"""
194 if value < 10**7:
195 return ('%.6f' % value)[:8]
196 else:
197 # value is HUGE very unlikely to happen (4+ month run)
198 return '%i' % value
199
200
201 _marker = object()
202
203
204 def printresult(variants, idx, data, maxidx, verbose=False, reference=_marker):
205 """print a line of result to stdout"""
206 mask = '%%0%ii) %%s' % idxwidth(maxidx)
207
208 out = []
209 for var in variants:
210 if data[var] is None:
211 out.append('error ')
212 out.append(' ' * 4)
213 continue
214 out.append(formattiming(data[var]['wall']))
215 if reference is not _marker:
216 factor = None
217 if reference is not None:
218 factor = getfactor(reference[var], data[var], 'wall')
219 out.append(formatfactor(factor))
220 if verbose:
221 out.append(formattiming(data[var]['comb']))
222 out.append(formattiming(data[var]['user']))
223 out.append(formattiming(data[var]['sys']))
224 out.append('%6d' % data[var]['count'])
225 print(mask % (idx, ' '.join(out)))
226
227
228 def printheader(variants, maxidx, verbose=False, relative=False):
229 header = [' ' * (idxwidth(maxidx) + 1)]
230 for var in variants:
231 if not var:
232 var = 'iter'
233 if len(var) > 8:
234 var = var[:3] + '..' + var[-3:]
235 header.append('%-8s' % var)
236 if relative:
237 header.append(' ')
238 if verbose:
239 header.append('%-8s' % 'comb')
240 header.append('%-8s' % 'user')
241 header.append('%-8s' % 'sys')
242 header.append('%6s' % 'count')
243 print(' '.join(header))
244
245
246 def getrevs(spec):
247 """get the list of rev matched by a revset"""
248 try:
249 out = check_output(['hg', 'log', '--template={rev}\n', '--rev', spec])
250 except subprocess.CalledProcessError as exc:
251 print("abort, can't get revision from %s" % spec, file=sys.stderr)
252 sys.exit(exc.returncode)
253 return [r for r in out.split() if r]
254
255
256 def applyvariants(revset, variant):
257 if variant == 'plain':
258 return revset
259 for var in variant.split('+'):
260 revset = '%s(%s)' % (var, revset)
261 return revset
262
263
264 helptext = """This script will run multiple variants of provided revsets using
265 different revisions in your mercurial repository. After the benchmark are run
266 summary output is provided. Use it to demonstrate speed improvements or pin
267 point regressions. Revsets to run are specified in a file (or from stdin), one
268 revsets per line. Line starting with '#' will be ignored, allowing insertion of
269 comments."""
270 parser = optparse.OptionParser(
271 usage="usage: %prog [options] <revs>", description=helptext
272 )
273 parser.add_option(
274 "-f",
275 "--file",
276 help="read revset from FILE (stdin if omitted)",
277 metavar="FILE",
278 )
279 parser.add_option("-R", "--repo", help="run benchmark on REPO", metavar="REPO")
280
281 parser.add_option(
282 "-v",
283 "--verbose",
284 action='store_true',
285 help="display all timing data (not just best total time)",
286 )
287
288 parser.add_option(
289 "",
290 "--variants",
291 default=','.join(DEFAULTVARIANTS),
292 help="comma separated list of variant to test "
293 "(eg: plain,min,sorted) (plain = no modification)",
294 )
295 parser.add_option(
296 '',
297 '--contexts',
298 action='store_true',
299 help='obtain changectx from results instead of integer revs',
300 )
301
302 (options, args) = parser.parse_args()
303
304 if not args:
305 parser.print_help()
306 sys.exit(255)
307
308 # the directory where both this script and the perf.py extension live.
309 contribdir = os.path.dirname(__file__)
310
311 revsetsfile = sys.stdin
312 if options.file:
313 revsetsfile = open(options.file)
314
315 revsets = [l.strip() for l in revsetsfile if not l.startswith('#')]
316 revsets = [l for l in revsets if l]
317
318 print("Revsets to benchmark")
319 print("----------------------------")
320
321 for idx, rset in enumerate(revsets):
322 print("%i) %s" % (idx, rset))
323
324 print("----------------------------")
325 print()
326
327 revs = []
328 for a in args:
329 revs.extend(getrevs(a))
330
331 variants = options.variants.split(',')
332
333 results = []
334 for r in revs:
335 print("----------------------------")
336 printrevision(r)
337 print("----------------------------")
338 update(r)
339 res = []
340 results.append(res)
341 printheader(variants, len(revsets), verbose=options.verbose)
342 for idx, rset in enumerate(revsets):
343 varres = {}
344 for var in variants:
345 varrset = applyvariants(rset, var)
346 data = perf(varrset, target=options.repo, contexts=options.contexts)
347 varres[var] = data
348 res.append(varres)
349 printresult(
350 variants, idx, varres, len(revsets), verbose=options.verbose
351 )
352 sys.stdout.flush()
353 print("----------------------------")
354
355
356 print(
357 """
358
359 Result by revset
360 ================
361 """
362 )
363
364 print('Revision:')
365 for idx, rev in enumerate(revs):
366 sys.stdout.write('%i) ' % idx)
367 sys.stdout.flush()
368 printrevision(rev)
369
370 print()
371 print()
372
373 for ridx, rset in enumerate(revsets):
374 print("revset #%i: %s" % (ridx, rset))
375 printheader(variants, len(results), verbose=options.verbose, relative=True)
376 ref = None
377 for idx, data in enumerate(results):
378 printresult(
379 variants,
380 idx,
381 data[ridx],
382 len(results),
383 verbose=options.verbose,
384 reference=ref,
385 )
386 ref = data[ridx]
387 print()