Debian Codegraph @

tests/compare_performance.py

raw
1 #!/usr/bin/env python3
2
3 """
4 compare the runtime performance of two different versions of Graphviz
5
6 When making changes to Graphviz’ code that may affect performance, you can use this
7 script to evaluate the effect of your changes:
8
9 python3 compare_performance.py \
10 /path/to/install/before/bin/dot /path/to/install/after/bin/dot
11
12 This will run various known expensive workloads and report the relative performance of
13 the two or more versions you gave it as tabulated results.
14 """
15
16 import argparse
17 import io
18 import os
19 import platform
20 import shlex
21 import shutil
22 import subprocess
23 import sys
24 import time
25 from pathlib import Path
26 from typing import Union
27
28 import tabulate
29
30 MY_DIR = Path(__file__).resolve().parent
31 """
32 path to our containing directory
33 """
34
35 TESTS: dict[str, list[Union[str, Path]]] = {
36 "#1172 1": ["dot", "-Ln3", "-Txdot", MY_DIR / "1172_1.xdot"],
37 "#1172 2": ["dot", "-Ln3", "-Txdot", MY_DIR / "1172_2.xdot"],
38 "#1652": ["neato", "-Tsvg", MY_DIR / "1652.dot"],
39 "#1718": ["circo", "-Tsvg", MY_DIR / "1718.dot"],
40 "#1864": ["neato", "-Tsvg", MY_DIR / "1864.dot"],
41 "#2064": [
42 "dot",
43 "-Gnslimit=2",
44 "-Gnslimit1=2",
45 "-Gmaxiter=5000",
46 "-Tsvg",
47 MY_DIR / "2064.dot",
48 ],
49 "#2095": ["dot", "-Tsvg", MY_DIR / "2095_1.dot"],
50 "#2108": ["dot", "-Tsvg", MY_DIR / "2108.dot"],
51 "#2222": ["dot", "-Tsvg", MY_DIR / "2222.dot"],
52 "#2343": ["dot", "-Tpng", MY_DIR / "2343.dot"],
53 "#2475 1": [
54 "dot",
55 "-Gnslimit=2",
56 "-Gnslimit1=2",
57 "-Gmclimit=.33",
58 "-Gremincross=false",
59 "-Gsearchsize=20",
60 "-Gsplines=false",
61 "-Tsvg",
62 MY_DIR / "2475_1.dot",
63 ],
64 "#2475 2": [
65 "dot",
66 "-Gnslimit=2",
67 "-Gnslimit1=2",
68 "-Gmclimit=.33",
69 "-Gremincross=false",
70 "-Gsearchsize=20",
71 "-Gsplines=false",
72 "-Tsvg",
73 MY_DIR / "2475_2.dot",
74 ],
75 "#2593": ["ccomps", MY_DIR / "2593.dot"],
76 "#2621": ["dot", "-Tpng", MY_DIR / "2621.dot"],
77 "#2646": ["dot", "-Tpdf", MY_DIR / "2646.dot"],
78 "!2854": ["dot", "-Tsvg", MY_DIR / "2854.dot"],
79 }
80 """
81 relevant workloads to evaluate
82
83 Entries are a test name mapped to a command to run. Commands will all have an
84 implicit `-o /dev/null` added to them when executed.
85 """
86
87
88 def run(args: list[Union[str, Path]], root: Union[str, Path]):
89 """
90 run a command, pre-echoing it like Bash’s `set -x`
91
92 Args:
93 args: Command line to run
94 root: Root directory of the Graphviz installation under test
95 """
96 assert len(args) > 0
97
98 exe = root / "bin"
99 lib = root / "lib"
100
101 env = os.environ.copy()
102 if platform.system() == "Darwin":
103 if "DYLD_LIBRARY_PATH" in env:
104 env["DYLD_LIBRARY_PATH"] = f"{lib}{os.pathsep}{env['DYLD_LIBRARY_PATH']}"
105 prefix = f'DYLD_LIBRARY_PATH="{lib}{os.pathsep}${{DYLD_LIBRARY_PATH}}"'
106 else:
107 env["DYLD_LIBRARY_PATH"] = str(lib)
108 prefix = f'DYLD_LIBRARY_PATH="{lib}"'
109 else:
110 if "LD_LIBRARY_PATH" in env:
111 env["LD_LIBRARY_PATH"] = f"{lib}{os.pathsep}{env['LD_LIBRARY_PATH']}"
112 prefix = f'LD_LIBRARY_PATH="{lib}{os.pathsep}${{LD_LIBRARY_PATH}}"'
113 else:
114 env["LD_LIBRARY_PATH"] = str(lib)
115 prefix = f'LD_LIBRARY_PATH="{lib}"'
116
117 arg0 = shutil.which(args[0], path=exe)
118 assert arg0 is not None, "{args[0]} not found in installation {root}"
119 argv = [arg0] + args[1:] + ["-o", os.devnull]
120
121 print(f"+ env {prefix} {shlex.join(str(x) for x in argv)}")
122 proc = subprocess.run(argv, check=False)
123 if proc.returncode != 0:
124 print(f"warning: command returned {proc.returncode}")
125
126
127 def pretty_time(duration: float):
128 """turn a count of seconds into XXhXXmXXs"""
129 hours = int(duration / 60 / 60)
130 minutes = int(duration / 60 % 60)
131 seconds = int(duration % 60)
132 return f"{hours}h{minutes:02}m{seconds:02}s"
133
134
135 def main(args: list[str]) -> int:
136 """entry point"""
137
138 # parse command line options
139 parser = argparse.ArgumentParser(description=__doc__)
140 parser.add_argument(
141 "candidate",
142 type=argparse.FileType("rb"),
143 nargs="+",
144 help="Graphviz binaries to compare",
145 )
146 options = parser.parse_args(args[1:])
147
148 # derive installation roots
149 roots = []
150 for dot in options.candidate:
151 exe = Path(dot.name).resolve()
152 roots += [exe.parents[1]]
153 headers = ["test case"] + roots
154
155 print(f"Comparing {[str(r) for r in roots]}…")
156
157 results: list[list[str]] = []
158 for name, cmd in TESTS.items():
159 result = []
160 for root in roots:
161 start = time.monotonic()
162 run(cmd, root)
163 stop = time.monotonic()
164 result += [stop - start]
165
166 # dump results progress, so that if the user interrupts they still have
167 # something partial to analyze
168 row = [name]
169 for index, r in enumerate(result):
170 cell = io.StringIO()
171 if index != 0:
172 if r < result[0]:
173 cell.write("\033[32m") # green
174 elif r > result[0]:
175 cell.write("\033[31m") # red
176 cell.write(pretty_time(r))
177 if index != 0:
178 cell.write(f" ({int((r - result[0]) / result[0] * 100)}%)\033[0m")
179 row += [cell.getvalue()]
180 print(
181 tabulate.tabulate(
182 results + [row], headers=headers, tablefmt="simple_outline"
183 )
184 )
185 results += [row]
186
187 return 0
188
189
190 if __name__ == "__main__":
191 sys.exit(main(sys.argv))