Debian Codegraph @

benchmark/run_benchmarks.py

raw
1 import collections
2 import io
3 import logging
4 import os
5 import pathlib
6 import re
7 import shutil
8 import subprocess
9 import sys
10 import tempfile
11 import time
12 import zipfile
13
14
15 BENCHMARKS_DIR = pathlib.Path(__file__).parent
16
17 BENCHMARK_FILES = sorted(BENCHMARKS_DIR.glob("bench_*.py"))
18
19 ALL_BENCHMARKS = [bm.stem for bm in BENCHMARK_FILES]
20
21 LIMITED_API_VERSION = max((3, 12), sys.version_info[:2])
22
23
24 try:
25 from distutils import sysconfig
26 DISTUTILS_CFLAGS = sysconfig.get_config_var('CFLAGS')
27 except ImportError:
28 DISTUTILS_CFLAGS = ''
29
30
31 parse_timings = re.compile(
32 r"(?P<lib>\w+):\s*"
33 r"(?P<benchmark>\w+)\s+"
34 r"\((?P<params>[^)]+)\)\s*"
35 r"(?P<besttime>[0-9.]+)\s+"
36 r"(?P<timings>.*)"
37 ).match
38
39
40 def run(command, cwd=None, pythonpath=None, c_macros=None):
41 env = None
42 if pythonpath:
43 env = os.environ.copy()
44 env['PYTHONPATH'] = pythonpath
45 if c_macros:
46 env = env or os.environ.copy()
47 env['CFLAGS'] = env.get('CFLAGS', '') + " " + ' '.join(f" -D{macro}" for macro in c_macros)
48
49 try:
50 return subprocess.run(command, cwd=cwd, check=True, capture_output=True, env=env)
51 except subprocess.CalledProcessError as exc:
52 logging.error(f"Command failed: {' '.join(map(str, command))}\nOutput:\n{exc.stderr.decode()}")
53 raise
54
55
56 def copy_benchmarks(bm_dir: pathlib.Path, benchmarks=None):
57 bm_files = []
58 shutil.copy(BENCHMARKS_DIR / 'benchbase.py', bm_dir / 'benchbase.py')
59 for bm_src_file in BENCHMARK_FILES:
60 if benchmarks and bm_src_file.stem not in benchmarks:
61 continue
62 bm_file = bm_dir / bm_src_file.name
63 for benchmark_file in BENCHMARKS_DIR.glob(bm_src_file.stem + ".*"):
64 shutil.copy(benchmark_file, bm_dir / benchmark_file.name)
65 bm_files.append(bm_file)
66
67 return bm_files
68
69
70 def compile_lxml(lxml_dir: pathlib.Path, c_macros=None):
71 rev_hash = get_git_rev(rev_dir=lxml_dir)
72 logging.info(f"Compiling lxml gitrev {rev_hash}")
73 run(
74 [sys.executable, "setup.py", "build_ext", "-i", "-j6"],
75 cwd=lxml_dir,
76 c_macros=c_macros,
77 )
78
79
80 def get_git_rev(revision=None, rev_dir=None):
81 command = ["git", "describe", "--long"]
82 if revision:
83 command.append(revision)
84 output = run(command, cwd=rev_dir)
85 _, rev_hash = output.stdout.decode().strip().rsplit('-', 1)
86 return rev_hash[1:]
87
88
89 def git_clone(rev_dir, revision):
90 rev_hash = get_git_rev(revision)
91 run(["git", "clone", "-n", "--no-single-branch", ".", str(rev_dir)])
92 run(["git", "checkout", rev_hash], cwd=rev_dir)
93
94
95 def copy_profile(bm_dir, module_name, profiler):
96 timestamp = int(time.time() * 1000)
97 profile_input = bm_dir / "profile.out"
98 data_file_name = f"{profiler}_{module_name}_{timestamp:X}.data"
99
100 if profiler == 'callgrind':
101 bm_dir_str = str(bm_dir) + os.sep
102 with open(profile_input) as data_file_in:
103 with open(data_file_name, mode='w') as data_file_out:
104 for line in data_file_in:
105 if bm_dir_str in line:
106 # Remove absolute file paths to link to local file copy below.
107 line = line.replace(bm_dir_str, "")
108 data_file_out.write(line)
109 else:
110 shutil.move(profile_input, data_file_name)
111
112 for result_file_name in (f"{module_name}.c", f"{module_name}.html"):
113 result_file = bm_dir / result_file_name
114 if result_file.exists():
115 shutil.move(result_file, result_file_name)
116
117 for ext in bm_dir.glob(f"{module_name}.*so"):
118 shutil.move(str(ext), ext.name)
119
120
121 def run_benchmark(bm_dir, module_name, pythonpath=None, profiler=None):
122 logging.info(f"Running benchmark '{module_name}'.")
123
124 command = []
125
126 if profiler:
127 if profiler == 'perf':
128 command = ["perf", "record", "--quiet", "-g", "--output=profile.out"]
129 elif profiler == 'callgrind':
130 command = [
131 "valgrind", "--tool=callgrind",
132 "--dump-instr=yes", "--collect-jumps=yes",
133 "--callgrind-out-file=profile.out",
134 ]
135
136 command += [sys.executable, f"{module_name}.py"]
137
138 output = run(command, cwd=bm_dir, pythonpath=pythonpath)
139
140 if profiler:
141 copy_profile(bm_dir, module_name, profiler)
142
143 lines = filter(None, output.stdout.decode().splitlines())
144 for line in lines:
145 if line == "Setup times for trees in seconds:":
146 break
147
148 other_lines = []
149 timings = []
150 for line in lines:
151 match = parse_timings(line)
152 if match:
153 timings.append((match['benchmark'], match['params'].strip(), match['lib'], float(match['besttime']), match['timings']))
154 else:
155 other_lines.append(line)
156
157 return other_lines, timings
158
159
160 def run_benchmarks(bm_dir, benchmarks, pythonpath=None, profiler=None):
161 timings = {}
162 for benchmark in benchmarks:
163 timings[benchmark] = run_benchmark(bm_dir, benchmark, pythonpath=pythonpath, profiler=profiler)
164 return timings
165
166
167 def benchmark_revisions(benchmarks, revisions, profiler=None, limited_revisions=(), deps_zipfile=None):
168 python_version = "Python %d.%d.%d" % sys.version_info[:3]
169 logging.info(f"### Comparing revisions in {python_version}: {' '.join(revisions)}.")
170 logging.info(f"CFLAGS={os.environ.get('CFLAGS', DISTUTILS_CFLAGS)}")
171
172 hashes = {}
173 timings = {}
174 for revision in revisions:
175 rev_hash = get_git_rev(revision)
176 if rev_hash in hashes:
177 logging.info(f"### Ignoring revision '{revision}': same as '{hashes[rev_hash]}'")
178 continue
179 hashes[rev_hash] = revision
180
181 logging.info(f"### Preparing benchmark run for lxml '{revision}'.")
182 timings[revision] = benchmark_revision(
183 revision, benchmarks, profiler, deps_zipfile=deps_zipfile)
184
185 if revision in limited_revisions:
186 logging.info(
187 f"### Preparing benchmark run for lxml '{revision}' (Limited API {LIMITED_API_VERSION[0]}.{LIMITED_API_VERSION[1]}).")
188 timings['L-' + revision] = benchmark_revision(
189 revision, benchmarks, profiler,
190 c_macros=["Py_LIMITED_API=0x%02x%02x0000" % LIMITED_API_VERSION],
191 deps_zipfile=deps_zipfile,
192 )
193
194 return timings
195
196
197 def cache_libs(lxml_dir, deps_zipfile):
198 for dir_path, _, filenames in (lxml_dir / "build" / "tmp").walk():
199 for filename in filenames:
200 path = dir_path / filename
201 deps_zipfile.write(path, path.relative_to(lxml_dir))
202
203
204 def benchmark_revision(revision, benchmarks, profiler=None, c_macros=None, deps_zipfile=None):
205 with tempfile.TemporaryDirectory() as base_dir_str:
206 base_dir = pathlib.Path(base_dir_str)
207 lxml_dir = base_dir / "lxml" / revision
208 bm_dir = base_dir / "benchmarks" / revision
209
210 git_clone(lxml_dir, revision=revision)
211
212 bm_dir.mkdir(parents=True)
213 bm_files = copy_benchmarks(bm_dir, benchmarks)
214
215 deps_zip_is_empty = deps_zipfile and not deps_zipfile.namelist()
216 if deps_zipfile and not deps_zip_is_empty:
217 deps_zipfile.extractall(lxml_dir)
218
219 compile_lxml(lxml_dir, c_macros=c_macros)
220
221 if deps_zipfile and deps_zip_is_empty:
222 cache_libs(lxml_dir, deps_zipfile)
223
224 logging.info(f"### Running benchmarks for {revision}: {' '.join(bm.stem for bm in bm_files)}")
225 return run_benchmarks(bm_dir, benchmarks, pythonpath=f"{bm_dir}:{lxml_dir / 'src'}", profiler=profiler)
226
227
228 def report_revision_timings(rev_timings):
229 units = {"nsec": 1e-9, "usec": 1e-6, "msec": 1e-3, "sec": 1.0}
230 scales = [(scale, unit) for unit, scale in reversed(units.items())] # biggest first
231
232 def format_time(t):
233 pos_t = abs(t)
234 for scale, unit in scales:
235 if pos_t >= scale:
236 break
237 else:
238 raise RuntimeError(f"Timing is below nanoseconds: {t:f}")
239 return f"{t / scale :+.3f} {unit}"
240
241 timings_by_benchmark = collections.defaultdict(list)
242 setup_times = []
243 for revision_name, bm_timings in rev_timings.items():
244 for benchmark_module, (output, timings) in bm_timings.items():
245 setup_times.append((benchmark_module, revision_name, output))
246 for benchmark_name, params, lib, best_time, result_text in timings:
247 timings_by_benchmark[(benchmark_module, benchmark_name, params)].append((lib, revision_name, best_time, result_text))
248
249 setup_times.sort()
250 for timings in timings_by_benchmark.values():
251 timings.sort()
252
253 for benchmark_module, revision_name, output in setup_times:
254 result = '\n'.join(output)
255 logging.info(f"Setup times for trees in seconds - {benchmark_module} / {revision_name}:\n{result}")
256
257 differences = collections.defaultdict(list)
258 for (benchmark_module, benchmark_name, params), timings in timings_by_benchmark.items():
259 logging.info(f"### Benchmark {benchmark_module} / {benchmark_name} ({params}):")
260 base_line = timings[0][2]
261 for lib, revision_name, bm_time, result_text in timings:
262 diff_str = ""
263 if base_line != bm_time:
264 pdiff = bm_time * 100 / base_line - 100
265 differences[(lib, revision_name)].append((abs(pdiff), pdiff, bm_time - base_line, benchmark_module, benchmark_name, params))
266 diff_str = f" {pdiff:+8.2f} %"
267 logging.info(
268 f" {lib:3} / {revision_name[:25]:25} = {bm_time:8.4f} {result_text}{diff_str}"
269 )
270
271 for (lib, revision_name), diffs in differences.items():
272 diffs.sort(reverse=True)
273 diffs_by_sign = {True: [], False: []}
274 for diff in diffs:
275 diffs_by_sign[diff[1] < 0].append(diff)
276
277 for is_win, diffs in diffs_by_sign.items():
278 if not diffs or diffs[0][0] < 1.0:
279 continue
280
281 logging.info(f"Largest {'gains' if is_win else 'losses'} for {revision_name}:")
282 cutoff = max(1.0, diffs[0][0] // 4)
283 for absdiff, pdiff, tdiff, benchmark_module, benchmark_name, params in diffs:
284 if absdiff < cutoff:
285 break
286 logging.info(f" {benchmark_module} / {benchmark_name:<25} ({params:>10}) {pdiff:+8.2f} % / {format_time(tdiff / 1000.0):>8}")
287
288
289 def parse_args(args):
290 from argparse import ArgumentParser, RawDescriptionHelpFormatter
291 parser = ArgumentParser(
292 description="Run benchmarks against different lxml tags/revisions.",
293 formatter_class=RawDescriptionHelpFormatter,
294 )
295 parser.add_argument(
296 "-b", "--benchmarks",
297 dest="benchmarks", default=','.join(ALL_BENCHMARKS),
298 help="The list of benchmark selectors to run, simple substrings, separated by comma.",
299 )
300 parser.add_argument(
301 "--with-limited",
302 dest="with_limited_api", action="append", default=[],
303 help="Also run the benchmarks for REVISION against the Limited C-API.",
304 )
305 #parser.add_argument(
306 # "--with-elementtree",
307 # dest="with_elementtree",
308 # help="Include results for Python's xml.etree.ElementTree.",
309 #)
310 parser.add_argument(
311 "--perf",
312 dest="profiler", action="store_const", const="perf", default=None,
313 help="Run Linux 'perf record' on the benchmark process.",
314 )
315 parser.add_argument(
316 "--callgrind",
317 dest="profiler", action="store_const", const="callgrind", default=None,
318 help="Run Valgrind's callgrind profiler on the benchmark process.",
319 )
320 parser.add_argument(
321 "revisions",
322 nargs="*", default=[],
323 help="The git revisions to check out and benchmark.",
324 )
325
326 return parser.parse_known_args(args)
327
328
329 if __name__ == '__main__':
330 options, cythonize_args = parse_args(sys.argv[1:])
331
332 logging.basicConfig(
333 stream=sys.stdout,
334 level=logging.INFO,
335 format="%(asctime)s %(message)s",
336 datefmt="%Y-%m-%d %H:%M:%S",
337 )
338
339 benchmark_selectors = set(bm.strip() for bm in options.benchmarks.split(","))
340 benchmarks = [bm for bm in ALL_BENCHMARKS if any(selector in bm for selector in benchmark_selectors)]
341 if benchmark_selectors and not benchmarks:
342 logging.error("No benchmarks selected!")
343 sys.exit(1)
344
345 deps_zipfile = zipfile.ZipFile(io.BytesIO(), mode='w')
346
347 revisions = list({rev: rev for rev in (options.revisions + options.with_limited_api)}) # deduplicate in order
348 timings = benchmark_revisions(
349 benchmarks, revisions,
350 profiler=options.profiler,
351 limited_revisions=options.with_limited_api,
352 deps_zipfile=deps_zipfile,
353 )
354 report_revision_timings(timings)