navid/veins / master / xveins/bench/core_bench.py
core_bench.py
← xveins/bench · 13654 bytes · raw · download
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import os
import platform
import random
import re
import shutil
import statistics
import subprocess
import sys
import tempfile
import time
from datetime import datetime, timezone
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 environment(binary: Path) -> str:
try:
return run([str(binary), "version"], Path.cwd()).strip()
except Exception:
return "unknown"
def cpu_name() -> str:
try:
return subprocess.run(
["sysctl", "-n", "machdep.cpu.brand_string"],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
check=True,
text=True,
).stdout.strip()
except Exception:
return platform.processor() or platform.machine()
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
root = Path(__file__).resolve().parents[2]
parser.add_argument("--spectre", type=Path, default=root / "veins" / "vn")
parser.add_argument(
"--cpp", type=Path, default=root / "veins-cpprewrite" / "build" / "vn"
)
parser.add_argument(
"--rust", type=Path, default=root / "veins-rust" / "target" / "release" / "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")
parser.add_argument("--markdown-out", type=Path)
args = parser.parse_args()
global PREFIX
PREFIX = [] if args.no_pin else command_prefix()
binaries = {
"rust": args.rust,
"cpp": args.cpp,
"spectre": args.spectre,
}
for label, binary in binaries.items():
if not binary.exists():
print(f"missing {label} binary: {binary}", file=sys.stderr)
return 2
work = Path(tempfile.mkdtemp(prefix="veins-core-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={'yes' if PREFIX else 'no'}"
)
rows: dict[str, list[tuple[float, float, int]]] = {
"rust": [],
"cpp": [],
"spectre": [],
}
for repeat in range(args.repeats):
print(f"repeat {repeat + 1}/{args.repeats}")
for label, binary in binaries.items():
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])
def spread(label: str, index: int) -> str:
values = [row[index] for row in rows[label]]
return (
f"{statistics.median(values):.3f} ({min(values):.3f}-{max(values):.3f})"
)
def spread_mib(label: str) -> str:
values = [row[2] / (1024 * 1024) for row in rows[label]]
return (
f"{statistics.median(values):.2f} ({min(values):.2f}-{max(values):.2f})"
)
values = {
label: (median(label, 0), median(label, 1), median(label, 2))
for label in rows
}
rust_commit, rust_checkout, rust_store = values["rust"]
cpp_commit, cpp_checkout, cpp_store = values["cpp"]
sx_commit, sx_checkout, sx_store = values["spectre"]
print()
print(f"commit C++/Rust: {cpp_commit / rust_commit:.2f}x")
print(f"commit Spectre/Rust: {sx_commit / rust_commit:.2f}x")
print(f"checkout C++/Rust: {cpp_checkout / rust_checkout:.2f}x")
print(f"checkout Spectre/Rust: {sx_checkout / rust_checkout:.2f}x")
print(f"store C++/Rust: {cpp_store / rust_store:.2f}x")
print(f"store Spectre/Rust: {sx_store / rust_store:.2f}x")
if args.markdown_out:
lines = [
f"Generated {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')} by `bench/core_bench.py`.",
"",
"### Environment",
"",
"| Implementation | Binary |",
"|:---|:---|",
f"| Rust | `{environment(args.rust)}` |",
f"| C++ | `{environment(args.cpp)}` |",
f"| Spectre | `{environment(args.spectre)}` |",
"",
"```",
f"host: {platform.system()} {platform.machine()}",
f"cpu: {cpu_name()}",
f"repeats: {args.repeats} (median reported)",
f"cpu pinning: {'yes' if PREFIX else 'no'}",
"```",
"",
"### Scope",
"",
"The Rust binary implements the local-core subset: `init`, `status`, `log`, "
"`go`/`commit`, `co`/`checkout`, `bmk set|ls|rm`, `self-test`, and `version`.",
"It uses the same FastCDC parameters, BLAKE3 object IDs, zstd level 1, "
"pack/index layout, operation log, and stat-cache invalidation window as "
"the reference.",
"",
"The subset does not implement merge/conflict objects, rebase/undo, the git "
"bridge, ignore files, or the network protocol. The workload below contains "
"no renames, ignores, merges, or network traffic, so the measured local "
"operations are directly comparable.",
"",
"### Workload",
"",
f"- Base snapshot: {size / (1024 * 1024):.2f} MiB, "
f"{args.small_files + 2} files.",
f"- {args.revisions} edit/commit revisions, {args.checkouts} checkouts, "
f"{args.repeats} repeats, median reported.",
"- Each revision rewrites about 1% of a 120,000-line generated C file "
"and three small module files.",
"- Each `go` performs the same snapshot, describe, and new-empty-change "
"sequence as the reference, including all operation-log writes.",
"- Store size includes `.veins` packs, indexes, operation heads, the native "
"commit map, and the stat cache.",
"",
"### Summary",
"",
"| Metric | Rust | C++ | Spectre | C++ / Rust | Spectre / Rust |",
"|:---|---:|---:|---:|---:|---:|",
f"| Commit total [s] | {spread('rust', 0)} | {spread('cpp', 0)} | "
f"{spread('spectre', 0)} | {cpp_commit / rust_commit:.2f}x | "
f"{sx_commit / rust_commit:.2f}x |",
f"| Checkout total [s] | {spread('rust', 1)} | {spread('cpp', 1)} | "
f"{spread('spectre', 1)} | {cpp_checkout / rust_checkout:.2f}x | "
f"{sx_checkout / rust_checkout:.2f}x |",
f"| Store size [MiB] | {spread_mib('rust')} | {spread_mib('cpp')} | "
f"{spread_mib('spectre')} | {cpp_store / rust_store:.2f}x | "
f"{sx_store / rust_store:.2f}x |",
"",
"Each cell is the median with the observed min-max range in parentheses.",
"A ratio above 1 means the other implementation took longer or used "
"more space than Rust.",
"",
"### Repeats",
"",
"| Repeat | Rust commit [s] | C++ commit [s] | Spectre commit [s] | "
"Rust checkout [s] | C++ checkout [s] | Spectre checkout [s] |",
"|:---|---:|---:|---:|---:|---:|---:|",
]
for index in range(args.repeats):
lines.append(
f"| {index + 1} | {rows['rust'][index][0]:.3f} | "
f"{rows['cpp'][index][0]:.3f} | {rows['spectre'][index][0]:.3f} | "
f"{rows['rust'][index][1]:.3f} | {rows['cpp'][index][1]:.3f} | "
f"{rows['spectre'][index][1]:.3f} |"
)
lines.extend(
[
"",
"### Notes",
"",
"- Both implementations use the same FastCDC parameters, BLAKE3 object IDs, "
"zstd level 1, pack/index layout, operation log, and stat-cache racy window.",
"- Each `go` performs the same snapshot, describe, and new-empty-change "
"sequence in both implementations, including three operation writes.",
"- The Rust subset omits ignore-file parsing and similarity-based rename "
"detection. This workload has neither ignore files nor renames, so both "
"implementations see the same file set and perform the same exact-rename scan.",
"- Rust and C++ store sizes are equal at this resolution; Spectre stores the "
"same logical history with a different packing policy.",
"- This is a single-machine run. Treat differences below roughly 5% as noise.",
"",
"### Reproduce",
"",
"```sh",
"cd veins-rust",
"cargo build --release",
"cd ../veins-cpprewrite",
"python3 bench/core_bench.py --repeats 5 --markdown-out bench/core_bench.md",
"```",
"",
]
)
args.markdown_out.write_text("\n".join(lines), encoding="utf-8")
return 0
finally:
shutil.rmtree(work, ignore_errors=True)
if __name__ == "__main__":
raise SystemExit(main())