navid/veins / b2c412f69b54c19975059840cf196fc8e7c4e022fdc4dd9fa5e2bb0472ff7c52 / xveins/bench/optim_bench.py

optim_bench.py

← xveins/bench · 13585 bytes · raw · download

#!/usr/bin/env python3

"""Compare a pre-optimization vn binary with the current C++ build."""

from __future__ import annotations

import argparse
import os
import platform
import random
import re
import shutil
import statistics
import subprocess
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, check: bool = True) -> 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=check,
        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,
    inner_runs: int,
) -> dict[str, float]:
    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_total = 0.0
    for revision in range(1, revisions + 1):
        mutate(repo, revision)
        commit_total += timed([str(binary), "go", "-m", f"revision {revision}"], repo)

    status_runs = []
    log_runs = []
    limited_runs = []
    for _ in range(inner_runs):
        status_runs.append(timed([str(binary), "status"], repo))
        log_runs.append(timed([str(binary), "log", "-no-col-titles"], repo))
        limited_runs.append(
            timed([str(binary), "log", "-l", "5", "-no-col-titles"], repo)
        )

    log_lines = run([str(binary), "log", "-no-col-titles"], repo).splitlines()
    targets = []
    for line in log_lines:
        parts = line.split()
        if parts and parts[0] == "@":
            if len(parts) < 3:
                continue
            target = parts[2]
        else:
            if len(parts) < 2:
                continue
            target = parts[1]
        if target not in targets:
            targets.append(target)
        if len(targets) >= checkouts:
            break

    checkout_total = 0.0
    for target in targets:
        checkout_total += timed([str(binary), "co", target], repo)

    return {
        "commit_total": commit_total,
        "status": statistics.median(status_runs),
        "log": statistics.median(log_runs),
        "log_limited": statistics.median(limited_runs),
        "checkout_total": checkout_total,
        "checkout_mean": checkout_total / max(1, len(targets)),
        "store_bytes": float(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:
        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 spread(values: list[float], digits: int) -> str:
    return (
        f"{statistics.median(values):.{digits}f} "
        f"({min(values):.{digits}f}-{max(values):.{digits}f})"
    )


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    root = Path(__file__).resolve().parents[1]
    parser.add_argument("--baseline", type=Path, required=True)
    parser.add_argument("--optimized", type=Path, default=root / "build" / "vn")
    parser.add_argument("--revisions", type=int, default=80)
    parser.add_argument("--checkouts", type=int, default=8)
    parser.add_argument("--repeats", type=int, default=5)
    parser.add_argument("--inner-runs", 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, default=root / "BENCH.md")
    args = parser.parse_args()

    global PREFIX
    PREFIX = [] if args.no_pin else command_prefix()

    binaries = {
        "baseline": args.baseline.resolve(),
        "optimized": args.optimized.resolve(),
    }
    for label, binary in binaries.items():
        if not binary.exists():
            print(f"missing {label} binary: {binary}")
            return 2

    work = Path(tempfile.mkdtemp(prefix="veins-optim-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, {args.revisions} revisions, "
            f"{args.checkouts} checkouts, {args.repeats} repeats"
        )
        rows: dict[str, list[dict[str, float]]] = {"baseline": [], "optimized": []}
        for repeat in range(args.repeats):
            print(f"repeat {repeat + 1}/{args.repeats}")
            for label, binary in binaries.items():
                row = bench_one(
                    binary,
                    work,
                    f"{label}-{repeat}",
                    args.revisions,
                    args.checkouts,
                    args.inner_runs,
                )
                rows[label].append(row)
                print(
                    f"  {label}: commit {row['commit_total']:.3f}s "
                    f"status {row['status'] * 1000:.1f}ms "
                    f"log {row['log'] * 1000:.1f}ms "
                    f"checkout {row['checkout_mean'] * 1000:.1f}ms"
                )

        def median(label: str, key: str) -> float:
            return statistics.median(row[key] for row in rows[label])

        def values(label: str, key: str) -> list[float]:
            return [row[key] for row in rows[label]]

        metrics = [
            ("Commit total [s]", "commit_total", 1.0, 4),
            ("Status [ms]", "status", 1000.0, 1),
            ("Log [ms]", "log", 1000.0, 1),
            ("Log -l 5 [ms]", "log_limited", 1000.0, 1),
            # store size below is converted with a fractional multiplier
            ("Checkout total [s]", "checkout_total", 1.0, 4),
            ("Checkout mean [ms]", "checkout_mean", 1000.0, 1),
            ("Store size [MiB]", "store_bytes", 1.0 / (1024.0 * 1024.0), 2),
        ]

        lines = [
            "# veins C++ optimization benchmark",
            "",
            f"Generated {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')} by "
            "`bench/optim_bench.py`.",
            "",
            "### Environment",
            "",
            "| Binary | Version |",
            "|:---|:---|",
            f"| Baseline | `{environment(args.baseline)}` |",
            f"| Optimized | `{environment(args.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"cpu pinning: {'yes' if PREFIX else 'no'}",
            f"temp dir:    {os.environ.get('TMPDIR', '(system default)')}",
            "```",
            "",
            "### 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.",
            "- Commit total covers all revision commits in the run.",
            "- Status and log are measured on the full history after the last commit.",
            "- Checkout walks the newest revisions in descending order.",
            "",
            "### Results",
            "",
            "| Metric | Baseline | Optimized | Speedup |",
            "|:---|---:|---:|---:|",
        ]
        for name, key, scale, digits in metrics:
            base_values = [value * scale for value in values("baseline", key)]
            opt_values = [value * scale for value in values("optimized", key)]
            base_med = statistics.median(base_values)
            opt_med = statistics.median(opt_values)
            if key == "store_bytes":
                ratio = base_med / opt_med
                ratio_text = (
                    f"{ratio:.2f}x smaller"
                    if ratio >= 1
                    else f"{1 / ratio:.2f}x larger"
                )
            else:
                ratio = base_med / opt_med
                ratio_text = f"{ratio:.2f}x"
            lines.append(
                f"| {name} | {spread(base_values, digits)} | "
                f"{spread(opt_values, digits)} | {ratio_text} |"
            )

        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.",
                "",
                "### Repeats",
                "",
                "| Repeat | Baseline status [ms] | Optimized status [ms] | "
                "Baseline log [ms] | Optimized log [ms] | "
                "Baseline checkout [ms] | Optimized checkout [ms] |",
                "|:---|---:|---:|---:|---:|---:|---:|",
            ]
        )
        for index in range(args.repeats):
            base = rows["baseline"][index]
            opt = rows["optimized"][index]
            lines.append(
                f"| {index + 1} | {base['status'] * 1000:.1f} | "
                f"{opt['status'] * 1000:.1f} | {base['log'] * 1000:.1f} | "
                f"{opt['log'] * 1000:.1f} | {base['checkout_mean'] * 1000:.1f} | "
                f"{opt['checkout_mean'] * 1000:.1f} |"
            )

        lines.extend(
            [
                "",
                "### Notes",
                "",
                "- The optimized build reads only the requested record from a pack instead "
                "of decoding the whole pack for every lookup.",
                "- Status and log memoize conflict-tree results and avoid flattening trees "
                "that are already equal.",
                "- Checkout reuses a single store, preloads indexes only, and skips rewriting "
                "files whose target object did not change.",
                "- Commit keeps the same object format, compression level, and operation-log "
                "sequence. Its gains come from fewer pack decodes and from writing the "
                "describe and new operations in one chained pack.",
                "- The baseline binary is the C++ build from before these changes. Rebuild "
                "each binary from its own source snapshot before reproducing.",
                "- This is a single-machine run. Treat differences below roughly 5% as noise.",
                "",
                "### Reproduce",
                "",
                "```sh",
                "cmake --build build -j",
                "python3 bench/optim_bench.py \\",
                "  --baseline /path/to/pre-optimization/vn \\",
                "  --optimized build/vn \\",
                "  --markdown-out 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())