111 lines
4.2 KiB
Python
111 lines
4.2 KiB
Python
#!/usr/bin/env python3
|
|
"""Check the Toolkit benchmark suite and compare it with the prior release."""
|
|
import argparse
|
|
import json
|
|
import math
|
|
import os
|
|
import re
|
|
import sys
|
|
|
|
# A Duration Debug token: a number immediately followed by a time unit, with the
|
|
# multi-char units listed before the bare "s" so alternation prefers them. The
|
|
# trailing (?![a-zA-Z]) stops "s" in words like "rows"/"cidrs" from matching.
|
|
_DUR = re.compile(r"([0-9]+(?:\.[0-9]+)?)\s*(ns|\u00b5s|us|ms|s)(?![a-zA-Z])")
|
|
_UNIT_NS = {"ns": 1.0, "us": 1e3, "\u00b5s": 1e3, "ms": 1e6, "s": 1e9}
|
|
_NAME = re.compile(r"^(?:test [A-Za-z0-9_:]+ \.\.\. )?(bench_[A-Za-z0-9_]+)\s*:")
|
|
EXPECTED_BENCHES = {
|
|
"bench_verify_artifact", "bench_naming_transforms",
|
|
"bench_parse_line_near_max_addrs", "bench_parse_targets_many_ranges_near_cap",
|
|
"bench_targets_to_cidrs_large_range", "bench_view_pipeline",
|
|
"bench_render_cells", "bench_health_diagnostics",
|
|
"bench_view_pipeline_default_sort", "bench_sort_by_each_column",
|
|
"bench_view_pipeline_with_filter", "bench_upsert_cold_start_population",
|
|
}
|
|
|
|
|
|
def parse_bench(text: str) -> dict:
|
|
"""Map each bench name to its timing in nanoseconds (the last Duration on the
|
|
line, since every bench prints its timing last)."""
|
|
out = {}
|
|
for line in text.splitlines():
|
|
m = _NAME.match(line.strip())
|
|
if not m:
|
|
continue
|
|
durs = _DUR.findall(line)
|
|
if not durs:
|
|
raise ValueError(f"missing timing for {m.group(1)}")
|
|
val, unit = durs[-1]
|
|
elapsed = float(val) * _UNIT_NS[unit]
|
|
if m.group(1) in out or not math.isfinite(elapsed) or elapsed <= 0:
|
|
raise ValueError(f"duplicate or invalid timing for {m.group(1)}")
|
|
out[m.group(1)] = elapsed
|
|
return out
|
|
|
|
|
|
def require_suite(results: dict) -> dict:
|
|
if results.keys() != EXPECTED_BENCHES:
|
|
raise ValueError("microbenchmark results differ from the declared suite")
|
|
return results
|
|
|
|
|
|
def benchmark_delta(current: dict, baseline: dict) -> float | None:
|
|
"""Average each comparable benchmark's percentage improvement."""
|
|
if not baseline:
|
|
return None
|
|
changes = [(baseline[name] - current[name]) / baseline[name]
|
|
for name in baseline]
|
|
delta = math.fsum(changes) / len(changes) * 100
|
|
if not math.isfinite(delta):
|
|
raise ValueError("benchmark comparison is not finite")
|
|
return delta
|
|
|
|
|
|
def main() -> int:
|
|
ap = argparse.ArgumentParser()
|
|
ap.add_argument("--current", required=True, help="captured bench stdout")
|
|
ap.add_argument("--baseline", required=True, help="baseline JSON (read + rewrite)")
|
|
ap.add_argument("--no-write", action="store_true", help="do not update the baseline")
|
|
args = ap.parse_args()
|
|
|
|
try:
|
|
with open(args.current, encoding="utf-8") as fh:
|
|
current = require_suite(parse_bench(fh.read()))
|
|
except (OSError, ValueError) as e:
|
|
print(f"bench-badge: cannot read current results: {e}", file=sys.stderr)
|
|
return 1
|
|
|
|
baseline = {}
|
|
try:
|
|
with open(args.baseline, encoding="utf-8") as fh:
|
|
baseline = json.load(fh)
|
|
except FileNotFoundError:
|
|
pass
|
|
except (OSError, ValueError) as e:
|
|
print(f"bench-badge: invalid baseline: {e}", file=sys.stderr)
|
|
return 1
|
|
if (not isinstance(baseline, dict)
|
|
or not set(baseline).issubset(current)
|
|
or any(not isinstance(value, (int, float)) or isinstance(value, bool)
|
|
or not math.isfinite(value) or value <= 0
|
|
for value in baseline.values())):
|
|
print("bench-badge: invalid or retired benchmark in baseline", file=sys.stderr)
|
|
return 1
|
|
|
|
try:
|
|
delta = benchmark_delta(current, baseline)
|
|
except ValueError as error:
|
|
print(f"bench-badge: {error}", file=sys.stderr)
|
|
return 1
|
|
print("NEW" if delta is None else f"{delta:.1f}")
|
|
|
|
if not args.no_write:
|
|
os.makedirs(os.path.dirname(args.baseline) or ".", exist_ok=True)
|
|
with open(args.baseline, "w", encoding="utf-8") as fh:
|
|
json.dump({k: round(v, 1) for k, v in sorted(current.items())}, fh, indent=2)
|
|
fh.write("\n")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|