#!/usr/bin/env python3 """Compute the weighted-average microbenchmark delta versus the previous release. Reads the captured stdout of `cargo test ... --ignored --nocapture bench_` (whose timings are Rust `Duration` Debug strings: "12.3ms", "512us"/"512µs", "840ns", "1.2s"), compares each bench to a committed baseline of the previous release's numbers, and prints the time-weighted average change as a signed percentage: (sum(current) / sum(baseline) - 1) * 100 over benches present in both Weighting by duration means the slow benches dominate, so the number tracks overall wall-time change rather than giving a tiny bench equal say. Then the baseline is rewritten with the current numbers, so the next release compares against this one ("the previous commit"). Usage: bench-badge.py --current bench-current.txt --baseline badges/bench-baseline.json Prints the delta as a plain number (e.g. "-3.2", or "NEW" when there is no usable baseline) to stdout. The baseline JSON lives under badges/ so committing it back does not trip compute-version.sh's path-based release bump. """ import argparse import json 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|µs|us|ms|s)(?![a-zA-Z])") _UNIT_NS = {"ns": 1.0, "us": 1e3, "µs": 1e3, "ms": 1e6, "s": 1e9} _NAME = re.compile(r"^(?:test [A-Za-z0-9_:]+ \.\.\. )?(bench_[A-Za-z0-9_]+)\s*:") 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: continue val, unit = durs[-1] out[m.group(1)] = float(val) * _UNIT_NS[unit] return out 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 = parse_bench(fh.read()) except OSError as e: print(f"bench-badge: cannot read current results: {e}", file=sys.stderr) print("NEW") return 0 if not current: print("bench-badge: no bench lines parsed from current results", file=sys.stderr) print("NEW") return 0 baseline = {} try: with open(args.baseline, encoding="utf-8") as fh: baseline = {k: float(v) for k, v in json.load(fh).items()} except (OSError, ValueError): baseline = {} common = [k for k in current if k in baseline and baseline[k] > 0] if common: sum_new = sum(current[k] for k in common) sum_old = sum(baseline[k] for k in common) delta = (sum_new / sum_old - 1.0) * 100.0 if sum_old > 0 else 0.0 print(f"{delta:.1f}") else: print("NEW") 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())