Debian Codegraph @

testsuite/perftest.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 """Compare the transfer performance of two rsync binaries (local <-> local).
3
4 This is a standalone dev tool (run it directly, not via runtests.py) for
5 spotting performance regressions between rsync releases. Given two rsync
6 binaries it builds one test tree, then runs the two binaries ALTERNATELY for a
7 number of loops, timing each transfer, and reports the mean and standard
8 deviation of the transfer time for each binary.
9
10 Two transfers are timed each loop (see --mode):
11 * full -- a fresh copy into an emptied destination (end-to-end read+write).
12 * noop -- a re-run against an already-synced destination (rsync's own
13 scan / file-list / stat overhead, where many regressions hide).
14
15 The first measured run of each binary is dropped (see --warmup) because it
16 cold-loads the source into the page cache and is an outlier.
17
18 The test tree's shape (heavy-tailed file sizes, a directory spine, symlinks,
19 hard links and a spread of permission modes) follows the gentestdata.py
20 generator; it is deterministic for a given --seed.
21
22 Examples:
23 # Quick smoke run, same binary twice (means should match, no regression).
24 ./perftest.py --files 200 --total-size 5M -n 3 ./rsync ./rsync
25
26 # Compare a released binary against a fresh build over 8 loops.
27 ./perftest.py -n 8 ../old_versions/rsync_3.4.0 ./rsync
28
29 # Heavier tree, no-op (scan-overhead) timing only.
30 ./perftest.py --files 50000 --total-size 2G --mode noop OLD/rsync NEW/rsync
31 """
32
33 import argparse
34 import dataclasses
35 import math
36 import os
37 import random
38 import shlex
39 import shutil
40 import statistics
41 import struct
42 import subprocess
43 import sys
44 import tempfile
45 import time
46
47 # ---------------------------------------------------------------------------
48 # Test-tree generation (ported from gentestdata.py, kept self-contained).
49 # ---------------------------------------------------------------------------
50
51 # Marker file at the tree root; safe_rmtree only deletes a tree carrying it.
52 MARKER = ".perftest"
53
54 # Permission modes drawn at random for regular files (execs + read-only).
55 FILE_MODES = [0o644, 0o644, 0o600, 0o640, 0o664, 0o444, 0o755, 0o750, 0o700]
56 # Directory modes; owner always keeps r-x so the tree stays traversable.
57 DIR_MODES = [0o755, 0o755, 0o775, 0o750, 0o700, 0o555]
58
59 SIZE_SIGMA = 1.8 # sigma of the underlying lognormal size distribution
60 BASE_BUF_SIZE = 1 << 20 # 1 MiB shared random buffer for file content
61
62
63 def parse_size(s):
64 """Parse a human size like 500M, 1.5GiB, 200KB, or a bare byte count."""
65 s = s.strip()
66 units = {
67 "": 1, "B": 1,
68 "K": 1024, "KIB": 1024, "KB": 1000,
69 "M": 1024**2, "MIB": 1024**2, "MB": 1000**2,
70 "G": 1024**3, "GIB": 1024**3, "GB": 1000**3,
71 "T": 1024**4, "TIB": 1024**4, "TB": 1000**4,
72 }
73 num, suffix = s, ""
74 while num and not (num[-1].isdigit() or num[-1] == "."):
75 suffix = num[-1] + suffix
76 num = num[:-1]
77 suffix = suffix.upper()
78 if suffix not in units:
79 raise argparse.ArgumentTypeError(f"unknown size suffix in {s!r}")
80 try:
81 value = float(num)
82 except ValueError:
83 raise argparse.ArgumentTypeError(f"invalid size {s!r}")
84 return int(value * units[suffix])
85
86
87 def human(n):
88 """Format a byte count for the summary output."""
89 for unit in ("B", "KiB", "MiB", "GiB", "TiB"):
90 if abs(n) < 1024 or unit == "TiB":
91 return f"{n:.1f}{unit}" if unit != "B" else f"{n}B"
92 n /= 1024
93
94
95 def gen_sizes(n, total, rng):
96 """Return n heavy-tailed file sizes (bytes) summing to exactly `total`."""
97 if n == 0:
98 return []
99 weights = [math.exp(rng.gauss(0.0, SIZE_SIGMA)) for _ in range(n)]
100 wsum = sum(weights)
101 sizes = [int(w / wsum * total) for w in weights]
102 drift = total - sum(sizes)
103 if drift and sizes:
104 i = max(range(n), key=lambda k: sizes[k])
105 sizes[i] += drift
106 return sizes
107
108
109 def build_dirs(root, num_dirs, max_depth, rng):
110 """Create `num_dirs` dirs under root, up to `max_depth` deep; return them."""
111 os.makedirs(root)
112 dirs = [root]
113 depth_of = {root: 0}
114 candidates = [root] if max_depth > 0 else []
115 counter = 0
116
117 cur = root
118 for d in range(1, max_depth + 1):
119 cur = os.path.join(cur, f"d{d}")
120 os.mkdir(cur)
121 dirs.append(cur)
122 depth_of[cur] = d
123 if d < max_depth:
124 candidates.append(cur)
125
126 while len(dirs) < num_dirs and candidates:
127 parent = rng.choice(candidates)
128 counter += 1
129 child = os.path.join(parent, f"dir{counter}")
130 os.mkdir(child)
131 d = depth_of[parent] + 1
132 dirs.append(child)
133 depth_of[child] = d
134 if d < max_depth:
135 candidates.append(child)
136
137 return dirs
138
139
140 def write_file(path, size, index, base):
141 """Write a regular file of exactly `size` bytes (index/size in first 16)."""
142 with open(path, "wb") as f:
143 remaining = size
144 if remaining >= 16:
145 f.write(struct.pack("<QQ", index, size))
146 remaining -= 16
147 blen = len(base)
148 while remaining > 0:
149 chunk = base if remaining >= blen else base[:remaining]
150 f.write(chunk)
151 remaining -= len(chunk)
152
153
154 def rel_symlink(target, link_path):
155 """Create a relative symlink at link_path pointing at target."""
156 rel = os.path.relpath(target, os.path.dirname(link_path))
157 os.symlink(rel, link_path)
158
159
160 def safe_rmtree(path):
161 """Remove a tree, even one containing read-only directories."""
162 for dirpath, _dirnames, _filenames in os.walk(path):
163 try:
164 os.chmod(dirpath, 0o700)
165 except OSError:
166 pass
167 shutil.rmtree(path)
168
169
170 def generate_tree(root, args):
171 """Build the deterministic source tree at `root`; return a summary string."""
172 n = args.files
173 num_dirs = args.dirs if args.dirs is not None else max(args.depth, n // 20, 1)
174 n_sym = args.symlinks if args.symlinks is not None else (max(1, n // 20) if n else 0)
175 n_hard = args.hardlinks if args.hardlinks is not None else (max(1, n // 20) if n else 0)
176
177 rng = random.Random(args.seed)
178 base = rng.randbytes(BASE_BUF_SIZE)
179
180 dirs = build_dirs(root, num_dirs, args.depth, rng)
181 with open(os.path.join(root, MARKER), "w") as f:
182 f.write(f"generated by perftest.py seed={args.seed} files={n} "
183 f"total={args.total_size}\n")
184
185 sizes = gen_sizes(n, args.total_size, rng)
186 files = []
187 for i in range(n):
188 path = os.path.join(rng.choice(dirs), f"file{i}.dat")
189 write_file(path, sizes[i], i, base)
190 files.append(path)
191
192 hard_made = 0
193 if files:
194 for i in range(n_hard):
195 tgt = rng.choice(files)
196 link = os.path.join(rng.choice(dirs), f"hlink{i}_{os.path.basename(tgt)}")
197 try:
198 os.link(tgt, link)
199 hard_made += 1
200 except OSError:
201 pass
202
203 sym_made = 0
204 for i in range(n_sym):
205 link = os.path.join(rng.choice(dirs), f"sym{i}")
206 roll = rng.random()
207 try:
208 if roll < 0.15 or not files:
209 os.symlink(f"../broken-target-{i}", link)
210 elif roll < 0.30:
211 rel_symlink(rng.choice(dirs), link)
212 else:
213 rel_symlink(rng.choice(files), link)
214 sym_made += 1
215 except OSError:
216 pass
217
218 for path in files:
219 os.chmod(path, rng.choice(FILE_MODES))
220 for path in sorted((d for d in dirs if d != root),
221 key=lambda p: p.count(os.sep), reverse=True):
222 os.chmod(path, rng.choice(DIR_MODES))
223
224 return (f"files={n} dirs={len(dirs)} symlinks={sym_made} hardlinks={hard_made} "
225 f"total={human(sum(sizes))} biggest={human(max(sizes) if sizes else 0)} "
226 f"seed={args.seed}")
227
228
229 # ---------------------------------------------------------------------------
230 # Benchmark.
231 # ---------------------------------------------------------------------------
232
233 @dataclasses.dataclass
234 class Binary:
235 label: str # "A" / "B"
236 path: str # absolute path to the rsync binary
237 version: str # first line of `rsync --version`
238
239
240 def rsync_version(path):
241 """Return the first line of `<rsync> --version`, or a placeholder."""
242 try:
243 r = subprocess.run([path, "--version"], capture_output=True, text=True, timeout=15)
244 line = (r.stdout or r.stderr or "").splitlines()
245 return line[0].strip() if line else "(no --version output)"
246 except (OSError, subprocess.TimeoutExpired) as e:
247 return f"(version unavailable: {e})"
248
249
250 def drop_caches():
251 """Best-effort: flush dirty pages and drop the page/dentry/inode caches.
252
253 Needs root to write /proc/sys/vm/drop_caches; returns True on success.
254 """
255 subprocess.run(["sync"], check=False)
256 try:
257 with open("/proc/sys/vm/drop_caches", "w") as f:
258 f.write("3\n")
259 return True
260 except OSError:
261 return False
262
263
264 def time_transfer(binary, rsync_args, src, dest, timeout):
265 """Run one `rsync <args> src/ dest/` and return its wall-clock seconds.
266
267 Raises RuntimeError if rsync exits non-zero (a failed transfer can't be
268 timed meaningfully).
269 """
270 argv = [binary.path, *rsync_args, src + "/", dest + "/"]
271 t0 = time.monotonic()
272 r = subprocess.run(argv, capture_output=True, text=True, timeout=timeout)
273 elapsed = time.monotonic() - t0
274 if r.returncode != 0:
275 raise RuntimeError(
276 f"{binary.label} ({binary.path}) rsync exited {r.returncode}:\n"
277 f" cmd: {shlex.join(argv)}\n"
278 f" {(r.stderr or r.stdout).strip()}")
279 return elapsed
280
281
282 def run_benchmark(binaries, args, src, dest_full, dest_noop):
283 """Run the alternating loops; return {label: {mode: [all samples]}}."""
284 do_full = args.mode in ("both", "full")
285 do_noop = args.mode in ("both", "noop")
286
287 # Pre-populate the shared no-op destination so every timed no-op run finds
288 # nothing to do. Use binary A; its content is identical for B.
289 if do_noop:
290 time_transfer(binaries[0], args.rsync_args, src, dest_noop, args.timeout)
291
292 samples = {b.label: {m: [] for m in ("full", "noop")} for b in binaries}
293 total_loops = args.warmup + args.runs
294
295 for loop in range(total_loops):
296 tag = "warmup" if loop < args.warmup else f"run {loop - args.warmup + 1}/{args.runs}"
297 # Alternate which binary goes first to cancel first-mover/thermal drift.
298 order = binaries if loop % 2 == 0 else list(reversed(binaries))
299 for b in order:
300 if do_full:
301 safe_rmtree(dest_full) if os.path.exists(dest_full) else None
302 os.mkdir(dest_full)
303 if args.drop_caches:
304 drop_caches()
305 t = time_transfer(b, args.rsync_args, src, dest_full, args.timeout)
306 samples[b.label]["full"].append(t)
307 _progress(b, "full", tag, t)
308 if do_noop:
309 if args.drop_caches:
310 drop_caches()
311 t = time_transfer(b, args.rsync_args, src, dest_noop, args.timeout)
312 samples[b.label]["noop"].append(t)
313 _progress(b, "noop", tag, t)
314 return samples
315
316
317 def _progress(binary, mode, tag, t):
318 excl = " (warmup, excluded)" if tag == "warmup" else ""
319 print(f" [{tag:>10}] {binary.label} {mode:<4} {t:8.3f}s{excl}")
320
321
322 # ---------------------------------------------------------------------------
323 # Reporting.
324 # ---------------------------------------------------------------------------
325
326 def _stats(times):
327 """(n, mean, stddev, min, median) over the timing samples."""
328 n = len(times)
329 if n == 0:
330 return (0, 0.0, 0.0, 0.0, 0.0)
331 return (n, statistics.mean(times),
332 statistics.stdev(times) if n > 1 else 0.0,
333 min(times), statistics.median(times))
334
335
336 def report(binaries, samples, args):
337 """Print the per-binary tables and the A-vs-B comparison; return exit code."""
338 print("\n" + "=" * 72)
339 for b in binaries:
340 print(f"{b.label}: {b.path}\n {b.version}")
341 print(f"rsync args: {' '.join(args.rsync_args)} "
342 f"(note: a full copy is not fsync'd unless you add --fsync)")
343 print("=" * 72)
344
345 modes = [m for m in ("full", "noop") if any(samples[b.label][m] for b in binaries)]
346 hdr = f"{'binary':<7}{'mode':<6}{'runs':>5}{'mean':>11}{'stddev':>11}{'min':>11}{'median':>11}"
347
348 for mode in modes:
349 print(f"\n{hdr}\n{'-' * len(hdr)}")
350 st = {}
351 for b in binaries:
352 # Drop the leading warm-up samples before computing statistics.
353 kept = samples[b.label][mode][args.warmup:]
354 st[b.label] = _stats(kept)
355 n, mean, sd, mn, md = st[b.label]
356 print(f"{b.label:<7}{mode:<6}{n:>5}{mean:>10.3f}s{sd:>10.3f}s"
357 f"{mn:>10.3f}s{md:>10.3f}s")
358
359 a, c = binaries[0].label, binaries[1].label
360 (na, ma, sda, *_), (nc, mc, sdc, *_) = st[a], st[c]
361 if na and nc and ma > 0:
362 delta = mc - ma
363 pct = delta / ma * 100.0
364 noise = max(sda, sdc)
365 # Flag only when B is slower beyond the run-to-run noise and a small
366 # relative threshold, so jitter doesn't cry "regression".
367 if delta > noise and pct > args.threshold:
368 verdict = f"REGRESSION (slower): {c} is {pct:+.1f}% vs {a}"
369 elif delta < -noise and -pct > args.threshold:
370 verdict = f"faster: {c} is {pct:+.1f}% vs {a}"
371 else:
372 verdict = f"no significant change: {pct:+.1f}% (within noise)"
373 print(f" {mode}: {a} {ma:.3f}s vs {c} {mc:.3f}s -> {verdict}")
374
375 if args.csv:
376 _write_csv(args.csv, binaries, samples)
377 print(f"\nraw per-run timings written to {args.csv}")
378 return 0
379
380
381 def _write_csv(path, binaries, samples):
382 with open(path, "w") as f:
383 f.write("binary,path,mode,run,warmup,seconds\n")
384 for b in binaries:
385 for mode in ("full", "noop"):
386 for i, t in enumerate(samples[b.label][mode]):
387 f.write(f"{b.label},{b.path},{mode},{i},{int(i == 0)},{t:.6f}\n")
388
389
390 # ---------------------------------------------------------------------------
391 # Main.
392 # ---------------------------------------------------------------------------
393
394 def main():
395 ap = argparse.ArgumentParser(
396 description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
397 ap.add_argument("rsync_a", help="path to the first rsync binary (labelled A)")
398 ap.add_argument("rsync_b", help="path to the second rsync binary (labelled B)")
399 ap.add_argument("-n", "--runs", type=int, default=10,
400 help="measured loops per binary (default: 10)")
401 ap.add_argument("--warmup", type=int, default=1,
402 help="leading runs per binary dropped from the stats to "
403 "reduce cache impact (default: 1)")
404 ap.add_argument("--mode", choices=("both", "full", "noop"), default="both",
405 help="full=clean-dest copy, noop=re-sync scan overhead, "
406 "both (default)")
407 ap.add_argument("--rsync-args", default="-aH",
408 help="rsync flags for the timed transfer (default: -aH)")
409 ap.add_argument("--threshold", type=float, default=2.0,
410 help="percent slowdown above run-to-run noise before a "
411 "regression is flagged (default: 2.0)")
412 # Tree-generation knobs (mirror gentestdata.py).
413 ap.add_argument("--src", default=None,
414 help="benchmark this existing tree instead of generating one")
415 ap.add_argument("-f", "--files", type=int, default=10000,
416 help="number of regular files to generate (default: 10000)")
417 ap.add_argument("-s", "--total-size", type=parse_size, default="500M",
418 help="total size of all regular files (default: 500M)")
419 ap.add_argument("-d", "--depth", type=int, default=10,
420 help="maximum directory tree depth (default: 10)")
421 ap.add_argument("--dirs", type=int, default=None,
422 help="number of directories (default: max(depth, files/20))")
423 ap.add_argument("--symlinks", type=int, default=None,
424 help="number of symlinks (default: files/20)")
425 ap.add_argument("--hardlinks", type=int, default=None,
426 help="number of hard links (default: files/20)")
427 ap.add_argument("--seed", type=int, default=1,
428 help="PRNG seed for a reproducible tree (default: 1)")
429 ap.add_argument("--workdir", default=None,
430 help="scratch root for src/dest dirs (default: a tempdir)")
431 ap.add_argument("--drop-caches", action="store_true",
432 help="sync + drop page/dentry/inode caches before each timed "
433 "run (needs root; cold-cache measurement)")
434 ap.add_argument("--timeout", type=float, default=3600.0,
435 help="seconds before a single rsync run is abandoned "
436 "(default: 3600)")
437 ap.add_argument("--keep", action="store_true",
438 help="keep the scratch tree on exit (default: remove it)")
439 ap.add_argument("--csv", default=None,
440 help="write raw per-run timings to this CSV file")
441 args = ap.parse_args()
442
443 if args.runs < 2:
444 ap.error("--runs must be >= 2 (need >=2 samples for a stddev)")
445 args.rsync_args = shlex.split(args.rsync_args)
446
447 binaries = []
448 for label, p in (("A", args.rsync_a), ("B", args.rsync_b)):
449 path = os.path.abspath(p)
450 if not (os.path.isfile(path) and os.access(path, os.X_OK)):
451 ap.error(f"rsync {label} is not an executable file: {p}")
452 binaries.append(Binary(label, path, rsync_version(path)))
453
454 workdir = tempfile.mkdtemp(prefix="rsync-perftest-",
455 dir=args.workdir) if not args.keep or not args.workdir \
456 else os.path.join(args.workdir, "rsync-perftest")
457 os.makedirs(workdir, exist_ok=True)
458 dest_full = os.path.join(workdir, "dest_full")
459 dest_noop = os.path.join(workdir, "dest_noop")
460 os.makedirs(dest_noop, exist_ok=True)
461
462 generated = None
463 if args.src:
464 src = os.path.abspath(args.src)
465 if not os.path.isdir(src):
466 ap.error(f"--src is not a directory: {args.src}")
467 print(f"using existing source tree {src}")
468 else:
469 src = os.path.join(workdir, "src")
470 print(f"generating source tree in {src} ...")
471 t0 = time.monotonic()
472 summary = generate_tree(src, args)
473 generated = src
474 print(f" {summary} ({time.monotonic() - t0:.1f}s)")
475
476 print(f"\nbenchmarking: warmup={args.warmup} runs={args.runs} mode={args.mode} "
477 f"drop_caches={args.drop_caches}\n")
478 rc = 1
479 try:
480 samples = run_benchmark(binaries, args, src, dest_full, dest_noop)
481 rc = report(binaries, samples, args)
482 except RuntimeError as e:
483 print(f"\nbenchmark aborted: {e}", file=sys.stderr)
484 rc = 2
485 except KeyboardInterrupt:
486 print("\ninterrupted", file=sys.stderr)
487 rc = 130
488 finally:
489 if args.keep:
490 print(f"\nkept scratch tree: {workdir}")
491 else:
492 for d in (dest_full, dest_noop, generated):
493 if d and os.path.exists(d):
494 safe_rmtree(d)
495 # Remove the workdir itself if it is now empty (i.e. we made it).
496 try:
497 os.rmdir(workdir)
498 except OSError:
499 pass
500 sys.exit(rc)
501
502
503 if __name__ == "__main__":
504 main()
505
506 # vim: sw=4 et ft=python