#!/usr/bin/env python3
# benchcmd - benchmark a command's runtime over N runs (average, min, max)
# Usage: benchcmd [-n N] [--warmup N] [--] COMMAND [ARGS...]
import argparse, os, shlex, statistics, subprocess, sys, time

def selftest():
    out = subprocess.run([sys.executable, os.path.abspath(__file__), "-n", "3", "true"],
                         capture_output=True, text=True)
    assert out.returncode == 0, out.stderr
    assert "average" in out.stdout.lower() and "runs" in out.stdout.lower(), out.stdout
    out = subprocess.run([sys.executable, os.path.abspath(__file__), "-n", "2", "false"],
                         capture_output=True, text=True)
    assert out.returncode != 0  # failing command should fail the benchmark
    out = subprocess.run([sys.executable, os.path.abspath(__file__), "-n", "2", "echo hi"],
                         capture_output=True, text=True)
    assert out.returncode == 0, out.stderr
    assert "average" in out.stdout.lower(), out.stdout
    print("benchcmd selftest: PASS")
    return 0

def main():
    ap = argparse.ArgumentParser(prog="benchcmd",
        description="Benchmark a command's runtime over N runs (average, min, max, median).")
    ap.add_argument("-n", "--runs", type=int, default=5, help="runs to time (default 5)")
    ap.add_argument("--warmup", type=int, default=0, help="untimed warmup runs (default 0)")
    ap.add_argument("--selftest", action="store_true", help="run built-in self-test and exit")
    ap.add_argument("cmd", nargs=argparse.REMAINDER, help="command to benchmark")
    a = ap.parse_args()
    if a.selftest:
        return selftest()
    cmd = [c for c in a.cmd if c != "--"]
    if len(cmd) == 1:
        # single quoted string, e.g. benchcmd -n 2 "echo hi"
        cmd = shlex.split(cmd[0])
    if not cmd:
        ap.error("a command to benchmark is required")
    if a.runs < 1:
        ap.error("-n must be at least 1")
    for _ in range(a.warmup):
        subprocess.run(cmd, capture_output=True)
    times = []
    for i in range(a.runs):
        t0 = time.monotonic()
        r = subprocess.run(cmd, capture_output=True)
        times.append(time.monotonic() - t0)
        if r.returncode != 0:
            print("benchcmd: run %d failed (exit %d); stopping." % (i + 1, r.returncode),
                  file=sys.stderr)
            return r.returncode
    times_ms = [t * 1000 for t in times]
    print("benchcmd: %s  (%d runs%s)" % (" ".join(cmd), a.runs,
          (", %d warmup" % a.warmup) if a.warmup else ""))
    print("  average: %.2f ms" % statistics.mean(times_ms))
    print("  median:  %.2f ms" % statistics.median(times_ms))
    print("  min:     %.2f ms" % min(times_ms))
    print("  max:     %.2f ms" % max(times_ms))
    if len(times_ms) > 1:
        print("  stddev:  %.2f ms" % statistics.stdev(times_ms))
    print("  total:   %.2f ms" % sum(times_ms))
    return 0

if __name__ == "__main__":
    sys.exit(main())
