navid/veins / master / xveins/bench/spectre_bench.py
spectre_bench.py
← xveins/bench · 13142 bytes · raw · download
#!/usr/bin/env python3
"""Compare a baseline vn binary with the current build on a real repository.
The default repository is ../spectre2, a 2,600-commit veins repository whose
pack index is large enough to make pack lookups the dominant cost of read-only
commands. A git import benchmark can be enabled with --git-source.
"""
from __future__ import annotations
import argparse
import os
import platform
import shutil
import statistics
import subprocess
import tempfile
import time
from datetime import datetime, timezone
from pathlib import Path
def cpu_name() -> str:
try:
with open("/proc/cpuinfo", encoding="utf-8") as handle:
for line in handle:
if line.startswith("model name"):
return line.split(":", 1)[1].strip()
except Exception:
pass
return platform.processor() or platform.machine()
def run(binary: Path, args: list[str], cwd: Path, check: bool = True) -> str:
env = os.environ.copy()
env["LC_ALL"] = "C"
env["NO_COLOR"] = "1"
env["NO_PROGRESS"] = "1"
result = subprocess.run(
[str(binary), *args],
cwd=str(cwd),
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=check,
text=True,
)
return result.stdout
def timed(binary: Path, args: list[str], cwd: Path) -> float:
start = time.perf_counter()
run(binary, args, cwd)
return time.perf_counter() - start
def spread(values: list[float], digits: int) -> str:
return (
f"{statistics.median(values):.{digits}f} "
f"({min(values):.{digits}f}-{max(values):.{digits}f})"
)
def command_median(binary: Path, args: list[str], cwd: Path, runs: int) -> float:
return statistics.median(timed(binary, args, cwd) for _ in range(runs))
def timed_git(args: list[str], cwd: Path) -> float:
env = os.environ.copy()
env["LC_ALL"] = "C"
env["GIT_PAGER"] = "cat"
start = time.perf_counter()
subprocess.run(
["git", "-C", str(cwd), *args],
env=env,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=True,
)
return time.perf_counter() - start
def version(binary: Path) -> str:
try:
return run(binary, ["version"], Path.cwd()).strip()
except Exception:
return "unknown"
def repo_info(binary: Path, repo: Path) -> tuple[int, int]:
pack_dir = repo / ".veins" / "store" / "packs"
pack_bytes = sum(path.stat().st_size for path in pack_dir.glob("*.vpack"))
try:
log = run(binary, ["log", "-l", "1000000", "-no-col-titles"], repo)
commits = max(0, len(log.splitlines()) - 1)
except Exception:
commits = 0
return commits, pack_bytes
def bench_import(binary: Path, git_source: Path, work: Path, label: str) -> float:
target = work / label
if target.exists():
shutil.rmtree(target)
start = time.perf_counter()
run(binary, ["init", str(target), f"-git-import:{git_source}"], work)
elapsed = time.perf_counter() - start
shutil.rmtree(target, ignore_errors=True)
return elapsed
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
root = Path(__file__).resolve().parents[1]
parser.add_argument(
"--repo",
type=Path,
default=root.parent.parent / "spectre2",
help="veins repository to benchmark (default: ../spectre2 next to the source tree)",
)
parser.add_argument("--baseline", type=Path, required=True)
parser.add_argument("--optimized", type=Path, default=root / "build" / "vn")
parser.add_argument("--repeats", type=int, default=7)
parser.add_argument("--inner-runs", type=int, default=3)
parser.add_argument(
"--git-source",
type=Path,
default=root.parent.parent / "spectre",
help="git repository used for the optional import benchmark",
)
parser.add_argument("--import-repeats", type=int, default=0)
parser.add_argument("--markdown-out", type=Path, default=root / "BENCH_SPECTRE.md")
args = parser.parse_args()
repo = args.repo.resolve()
baseline = args.baseline.resolve()
optimized = args.optimized.resolve()
for label, binary in (("baseline", baseline), ("optimized", optimized)):
if not binary.exists():
print(f"missing {label} binary: {binary}")
return 2
if not (repo / ".veins").is_dir():
print(f"not a veins repository: {repo}")
return 2
commands = {
"log": ["log"],
"log_l1": ["log", "-l", "1"],
"log_l1000": ["log", "-l", "1000"],
"status": ["status"],
"show": ["show"],
}
# Make sure both binaries agree before timing anything.
for name, command in commands.items():
reference = run(baseline, command, repo)
candidate = run(optimized, command, repo)
if reference != candidate:
print(f"output mismatch for vn {' '.join(command)} in {repo}")
return 3
print(f"repository: {repo}")
commits, pack_bytes = repo_info(optimized, repo)
print(f"commits: {commits}, packs: {pack_bytes / (1024 * 1024):.1f} MiB")
rows: dict[str, dict[str, list[float]]] = {
name: {"baseline": [], "optimized": []} for name in commands
}
for repeat in range(args.repeats):
print(f"repeat {repeat + 1}/{args.repeats}")
for name, command in commands.items():
for label, binary in (("baseline", baseline), ("optimized", optimized)):
value = command_median(binary, command, repo, args.inner_runs)
rows[name][label].append(value)
base_ms = statistics.median(rows[name]["baseline"]) * 1000
opt_ms = statistics.median(rows[name]["optimized"]) * 1000
print(f" {name:<10} baseline {base_ms:7.1f}ms optimized {opt_ms:7.1f}ms")
import_rows: dict[str, list[float]] = {"baseline": [], "optimized": []}
if args.import_repeats > 0:
if not (args.git_source / ".git").is_dir():
print(f"--git-source is not a git repository: {args.git_source}")
return 2
work = Path(tempfile.mkdtemp(prefix="veins-spectre-import-"))
try:
for label, binary in (("baseline", baseline), ("optimized", optimized)):
print(f"import warmup {label}")
bench_import(binary, args.git_source.resolve(), work, f"warmup-{label}")
for repeat in range(args.import_repeats):
print(f"import repeat {repeat + 1}/{args.import_repeats}")
order = [("baseline", baseline), ("optimized", optimized)]
if repeat % 2 == 1:
order.reverse()
for label, binary in order:
value = bench_import(
binary, args.git_source.resolve(), work, f"{label}-{repeat}"
)
import_rows[label].append(value)
print(f" import {label:<9} {value:.3f}s")
finally:
shutil.rmtree(work, ignore_errors=True)
git_reference: dict[str, float] = {}
git_source = args.git_source.resolve()
if (git_source / ".git").is_dir():
print("git reference")
for name, git_args in (
("log", ["log", "-n", "20"]),
("log_l1", ["log", "-n", "1"]),
("log_l1000", ["log", "-n", "1000"]),
("log_full", ["log"]),
):
values = [timed_git(git_args, git_source) for _ in range(args.inner_runs)]
git_reference[name] = statistics.median(values)
print(f" git {name:<10} {git_reference[name] * 1000:7.1f}ms")
names = {
"log": "Log [ms]",
"log_l1": "Log -l 1 [ms]",
"log_l1000": "Log -l 1000 [ms]",
"status": "Status [ms]",
"show": "Show [ms]",
}
lines = [
"# veins C++ spectre benchmark",
"",
f"Generated {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')} by "
"`bench/spectre_bench.py`.",
"",
"### Environment",
"",
"| Binary | Version | Path |",
"|:---|:---|:---|",
f"| Baseline | `{version(baseline)}` | `{baseline}` |",
f"| Optimized | `{version(optimized)}` | `{optimized}` |",
"",
"```",
f"host: {platform.system()} {platform.machine()}",
f"cpu: {cpu_name()}",
f"repeats: {args.repeats} (median reported)",
f"inner runs: {args.inner_runs} per command per repeat",
f"repository: {repo}",
f"commits: {commits}",
f"pack bytes: {pack_bytes / (1024 * 1024):.1f} MiB",
"```",
"",
"### Workload",
"",
"- Read-only commands run against an existing veins repository with a large pack.",
"- Each cell is the median of the per-repeat command medians.",
"- Progress output is disabled; both binaries write to a pipe.",
"- Baseline and optimized outputs are compared byte-for-byte before timing.",
]
if args.import_repeats > 0:
lines.append(
f"- Git import runs {args.import_repeats}x from `{args.git_source.resolve()}` "
"into a fresh temporary repository."
)
lines.extend(
[
"",
"### Results",
"",
"| Metric | Baseline | Optimized | Speedup |",
"|:---|---:|---:|---:|",
]
)
for name in commands:
base_values = [value * 1000 for value in rows[name]["baseline"]]
opt_values = [value * 1000 for value in rows[name]["optimized"]]
base_med = statistics.median(base_values)
opt_med = statistics.median(opt_values)
ratio = base_med / opt_med if opt_med > 0 else float("inf")
lines.append(
f"| {names[name]} | {spread(base_values, 1)} | "
f"{spread(opt_values, 1)} | {ratio:.2f}x |"
)
if import_rows["baseline"]:
base_values = import_rows["baseline"]
opt_values = import_rows["optimized"]
base_med = statistics.median(base_values)
opt_med = statistics.median(opt_values)
ratio = base_med / opt_med if opt_med > 0 else float("inf")
lines.append(
f"| Git import [s] | {spread(base_values, 3)} | "
f"{spread(opt_values, 3)} | {ratio:.2f}x |"
)
lines.extend(
[
"",
"Each cell is the median with the observed min-max range in parentheses.",
"A speedup above 1 means the optimized binary was faster.",
]
)
if git_reference:
lines.extend(
[
"",
"### Git reference",
"",
f"Timed against `{git_source}` with the same machine and warm cache.",
"",
"| Command | Median |",
"|:---|---:|",
f"| `git log -n 20` | {git_reference['log'] * 1000:.1f} ms |",
f"| `git log -n 1` | {git_reference['log_l1'] * 1000:.1f} ms |",
f"| `git log -n 1000` | {git_reference['log_l1000'] * 1000:.1f} ms |",
f"| `git log` (all) | {git_reference['log_full'] * 1000:.1f} ms |",
]
)
lines.extend(
[
"",
"### Notes",
"",
"- Pack reads keep one file descriptor per pack and use positional reads. "
"The baseline reopened and seeked the pack for every record header and body.",
"- Log no longer computes conflict state for commits outside the requested "
"window, and divergence detection is linear instead of quadratic.",
"- `git log -n N` truncates by date after reading N commits. `vn log` still "
"walks the full reachable graph so every child is printed before its parents; "
"compare it with full `git log` rather than `git log -n 20`.",
"- Git import, git materialize, cloning, and push report progress on stderr "
"when stderr is a terminal. Progress output is suppressed for pipes, so the "
"timings above are unaffected by it.",
"- Git import is dominated by copying the mirror and reading git objects, not "
"by veins pack lookups. It is not part of this optimization; enable it with "
"`--import-repeats N` when you want a rough import timing.",
"- This is a single-machine run. Treat differences below roughly 5% as noise.",
"",
"### Reproduce",
"",
"```sh",
"cmake --build build -j",
"python3 bench/spectre_bench.py \\",
" --baseline /path/to/pre-optimization/vn \\",
" --repo /path/to/spectre2 \\",
" --markdown-out BENCH_SPECTRE.md",
"```",
"",
]
)
args.markdown_out.write_text("\n".join(lines), encoding="utf-8")
print(f"wrote {args.markdown_out}")
return 0
if __name__ == "__main__":
raise SystemExit(main())