Debian Codegraph @

cachegrind.py

raw
1 #!/usr/bin/env python3
2
3 # Based on https://github.com/pythonspeed/cachegrind-benchmarking/blob/main/cachegrind.py
4 """
5 Run a program under Cachegrind, combining various metrics into one single performance metric.
6
7 License: https://opensource.org/licenses/MIT
8
9 ## Features
10
11 * Disables ASLR.
12 * Sets consistent cache sizes.
13 * Calculates a combined performance metric.
14
15 For more information see the detailed write up at:
16
17 https://pythonspeed.com/articles/consistent-benchmarking-in-ci/
18
19 ## Usage
20
21 $ python3 cachegrind.py ./yourprogram --yourparam=yourvalues
22
23 If you're benchmarking Python, make sure to set PYTHONHASHSEED to a fixed value
24 (e.g. `export PYTHONHASHSEED=1234`). Other languages may have similar
25 requirements to reduce variability.
26
27 The last line printed will be a combined performance metric, but you can tweak
28 the script to extract more info, or use it as a library.
29
30 Copyright © 2020, Hyphenated Enterprises LLC.
31 """
32
33 from __future__ import annotations
34
35 import os
36 import subprocess as sp
37 import sys
38 import typing as t
39 from pathlib import Path
40 from tempfile import NamedTemporaryFile
41
42
43 try:
44 sp.check_call(['setarch', '-h'], stdout=sp.DEVNULL, stderr=sp.DEVNULL)
45 sp.check_call(['valgrind', '-h'], stdout=sp.DEVNULL, stderr=sp.DEVNULL)
46 except FileNotFoundError as exc: # e.g. macOS
47 raise SystemExit(f'Command not found: {exc.filename}') from None
48
49 ARCH = sp.check_output(['uname', '-m'], text=True).strip()
50 DISABLE_ASLR_CMD = ['setarch', ARCH, '-R']
51
52
53 def run_with_cachegrind(args_list: list[str]) -> tuple[int, dict[str, int]]:
54 """
55 Run the the given program and arguments under Cachegrind, parse the
56 Cachegrind specs.
57
58 Return the program's exit status along with the parsed results.
59
60 For now we just ignore program output, and in general this is not robust.
61 """
62 # Deliberately not a context manager: this stays open across the run below, which writes to
63 # it, and is read afterwards.
64 temp_file = NamedTemporaryFile('r+', encoding='utf-8') # ruff: ignore[open-file-with-context-handler]
65 # Don't raise if the program fails (to support e.g. `pytest --benchmark-compare-fail=...`),
66 # but do return its status so that main() can exit with it. Callers such as the benchmark
67 # workflow rely on it to tell a benchmark regression from a clean run.
68 returncode = sp.call([
69 *DISABLE_ASLR_CMD,
70 'valgrind',
71 '--tool=cachegrind',
72 '--cache-sim=yes',
73 # Set some reasonable L1 and LL values, based on Haswell.
74 # Feel free to update, important part is that they are consistent across runs,
75 # instead of the default of copying from the current machine.
76 '--I1=32768,8,64',
77 '--D1=32768,8,64',
78 '--LL=8388608,16,64',
79 '--cachegrind-out-file=' + temp_file.name,
80 *args_list,
81 ])
82 return returncode, parse_cachegrind_output(temp_file)
83
84
85 def parse_cachegrind_output(temp_file: t.IO[str]) -> dict[str, int]:
86 header = summary = ''
87 for line in temp_file:
88 if line.startswith('events: '):
89 header = line[len('events: ') :].strip()
90 elif line.startswith('summary: '):
91 summary = line[len('summary:') :].strip()
92 assert header
93 assert summary
94 return dict(zip(header.split(), (int(i) for i in summary.split()), strict=False))
95
96
97 def get_counts(cg_results: dict[str, int]) -> dict[str, int]:
98 """
99 Given the result of run_with_cachegrind(), figure out the parameters we will use for final
100 estimate.
101
102 We pretend there's no L2 since Cachegrind doesn't currently support it.
103
104 Caveats: we're not including time to process instructions, only time to
105 access instruction cache(s), so we're assuming time to fetch and run_with_cachegrind
106 instruction is the same as time to retrieve data if they're both to L1
107 cache.
108 """
109 result = {}
110 d = cg_results
111
112 ram_hits = d['DLmr'] + d['DLmw'] + d['ILmr']
113
114 l3_hits = d['I1mr'] + d['D1mw'] + d['D1mr'] - ram_hits
115
116 total_memory_rw = d['Ir'] + d['Dr'] + d['Dw']
117 l1_hits = total_memory_rw - l3_hits - ram_hits
118 assert total_memory_rw == l1_hits + l3_hits + ram_hits
119
120 result['l1'] = l1_hits
121 result['l3'] = l3_hits
122 result['ram'] = ram_hits
123
124 return result
125
126
127 def combined_instruction_estimate(counts: dict[str, int]) -> int:
128 """
129 Given the result of run_with_cachegrind(), return estimate of total time to run_with_cachegrind.
130
131 Multipliers were determined empirically, but some research suggests they're
132 a reasonable approximation for cache time ratios. L3 is probably too low,
133 but then we're not simulating L2...
134 """
135 return counts['l1'] + (5 * counts['l3']) + (35 * counts['ram'])
136
137
138 def main() -> None:
139 returncode, results = run_with_cachegrind(sys.argv[1:])
140 counts = get_counts(results)
141 estimate = combined_instruction_estimate(counts)
142 print(f'{"*" * 80}\nCombined instruction estimate: {estimate:,}')
143 # Unlike the wall-clock figures pytest-benchmark records, which vary with whatever else is
144 # running on the machine, this estimate counts instructions and so is reproducible. Write it
145 # out when asked, so a caller can compare it between revisions without a noise allowance.
146 estimate_out = os.environ.get('CACHEGRIND_ESTIMATE_OUT')
147 if estimate_out:
148 Path(estimate_out).write_text(f'{estimate}\n', encoding='utf-8')
149 sys.exit(returncode)
150
151
152 if __name__ == '__main__':
153 main()