#!/usr/bin/env python3 """Compare the C++ and Spectre veins binaries on a synthetic edit workload.""" from __future__ import annotations import argparse import os import random import re import shutil import statistics import subprocess import sys import tempfile import time from pathlib import Path HEX12 = re.compile(r"\b[0-9a-f]{12}\b") def command_prefix() -> list[str]: try: subprocess.run( ["taskset", "-c", "0", "true"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True, ) return ["taskset", "-c", "0"] except Exception: return [] PREFIX: list[str] = [] def run(cmd: list[str], cwd: Path) -> str: env = os.environ.copy() env["LC_ALL"] = "C" env["NO_COLOR"] = "1" result = subprocess.run( [str(part) for part in PREFIX + cmd], cwd=str(cwd), env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True, text=True, ) return result.stdout def timed(cmd: list[str], cwd: Path) -> float: start = time.perf_counter() run(cmd, cwd) return time.perf_counter() - start def make_base(root: Path, lines: int, small_files: int) -> None: root.mkdir(parents=True) (root / "generated.c").write_text( "".join(f"int value_{i} = {i * 3 + 7};\n" for i in range(lines)), encoding="utf-8", ) for i in range(small_files): (root / f"module_{i:03d}.c").write_text( f"// module {i}\nint module_{i}(void) {{ return {i}; }}\n", encoding="utf-8" ) (root / "sub").mkdir() (root / "sub" / "nested.txt").write_text("nested\n" * 200, encoding="utf-8") def mutate(root: Path, revision: int) -> None: path = root / "generated.c" lines = path.read_text(encoding="utf-8").splitlines(keepends=True) rng = random.Random(revision) for _ in range(max(1, len(lines) // 100)): index = rng.randrange(len(lines)) lines[index] = f"int changed_{revision}_{index} = {revision};\n" path.write_text("".join(lines), encoding="utf-8") for i in range(3): (root / f"module_{i:03d}.c").write_text( f"// module {i}, revision {revision}\n" f"int module_{i}(void) {{ return {revision * 1000 + i}; }}\n", encoding="utf-8", ) def tree_bytes(root: Path) -> int: return sum(path.stat().st_size for path in root.rglob("*") if path.is_file()) def bench_one( binary: Path, work: Path, label: str, revisions: int, checkouts: int ) -> tuple[float, float, int]: repo = work / label shutil.copytree(work / "base", repo) run([str(binary), "init"], repo) (repo / ".veins" / "config").write_text( "user.name = Bench\nuser.email = bench@example.com\n", encoding="utf-8" ) mutate(repo, 0) run([str(binary), "go", "-m", "warmup"], repo) commit_time = 0.0 for revision in range(1, revisions + 1): mutate(repo, revision) commit_time += timed([str(binary), "go", "-m", f"revision {revision}"], repo) log_lines = run([str(binary), "log", "-no-col-titles"], repo).splitlines() ids = [match.group(0) for line in log_lines if (match := HEX12.search(line))] targets = ids[: max(1, checkouts)] checkout_time = 0.0 for i in range(checkouts): target = targets[min(i, len(targets) - 1)] checkout_time += timed([str(binary), "co", target], repo) return commit_time, checkout_time, tree_bytes(repo / ".veins") def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--spectre", type=Path, default=Path(__file__).resolve().parents[2] / "veins" / "vn", ) parser.add_argument( "--cpp", type=Path, default=Path(__file__).resolve().parents[1] / "build" / "vn" ) parser.add_argument("--revisions", type=int, default=20) parser.add_argument("--checkouts", type=int, default=8) parser.add_argument("--repeats", type=int, default=3) parser.add_argument("--large-lines", type=int, default=120000) parser.add_argument("--small-files", type=int, default=40) parser.add_argument("--no-pin", action="store_true") args = parser.parse_args() global PREFIX PREFIX = [] if args.no_pin else command_prefix() if not args.spectre.exists(): print(f"missing Spectre binary: {args.spectre}", file=sys.stderr) return 2 if not args.cpp.exists(): print(f"missing C++ binary: {args.cpp}", file=sys.stderr) return 2 work = Path(tempfile.mkdtemp(prefix="veins-bench-")) try: make_base(work / "base", args.large_lines, args.small_files) size = tree_bytes(work / "base") print( f"workload: {size / (1024 * 1024):.2f} MiB, " f"{args.revisions} revisions, {args.checkouts} checkouts, " f"{args.repeats} repeats, cpu pinning={'no' if args.no_pin else 'yes'}" ) rows: dict[str, list[tuple[float, float, int]]] = {"spectre": [], "cpp": []} for repeat in range(args.repeats): print(f"repeat {repeat + 1}/{args.repeats}") for label, binary in (("spectre", args.spectre), ("cpp", args.cpp)): commit, checkout, store = bench_one( binary, work, f"{label}-{repeat}", args.revisions, args.checkouts ) rows[label].append((commit, checkout, store)) print( f" {label}: commit {commit:.3f}s checkout {checkout:.3f}s " f"store {store / (1024 * 1024):.2f} MiB" ) def median(label: str, index: int) -> float: return statistics.median(row[index] for row in rows[label]) spectre_commit = median("spectre", 0) cpp_commit = median("cpp", 0) spectre_checkout = median("spectre", 1) cpp_checkout = median("cpp", 1) print() print(f"commit speedup C++/Spectre: {spectre_commit / cpp_commit:.2f}x") print(f"checkout speedup C++/Spectre: {spectre_checkout / cpp_checkout:.2f}x") print( f"store size ratio C++/Spectre: " f"{median('cpp', 2) / median('spectre', 2):.2f}x" ) return 0 finally: shutil.rmtree(work, ignore_errors=True) if __name__ == "__main__": raise SystemExit(main())