#!/bin/sh
# Runs the pic benchmarks and compares medians with this machine's baseline.
# Usage: pic-bench.sh BENCH_BINARY PIC_BINARY [--record]
#   PIC_BENCH_TOLERANCE  percent a median may grow before failing (default 50)
#   PIC_BENCH_FLOOR_US   medians below this are too noisy to judge (default 200)
#   PIC_BENCH_SCALE      multiplies the run counts (default 1)
#   PIC_BENCH_MACHINE    baseline name (default: OS-architecture)
set -eu
bench=$1
pic=$2
here=$(cd "$(dirname "$0")" && pwd)
# Baselines are per platform, not per host name (the repository is public).
baseline="$here/baselines/${PIC_BENCH_MACHINE:-$(uname -s)-$(uname -m)}.tsv"
out=build/pic/bench.tsv
mkdir -p build/pic
"$bench" "$pic" "${PIC_BENCH_SCALE:-1}" > "$out"
if [ "${3:-}" = --record ]; then
    mkdir -p "$here/baselines"
    cp "$out" "$baseline"
    printf 'recorded %s\n' "$baseline"
    exit 0
fi
if [ ! -f "$baseline" ]; then
    column -t < "$out"
    printf 'no baseline for this machine; record one with: make bench-pic-record\n'
    exit 0
fi
compare() {
    awk -F '\t' -v tol="${PIC_BENCH_TOLERANCE:-50}" -v floor="${PIC_BENCH_FLOOR_US:-200}" '
        NR == FNR { base[$1] = $2; next }
        {
            b = base[$1]
            if (b == "") { printf "%-22s %10s us  (new)\n", $1, $2; next }
            change = b > 0 ? ($2 - b) * 100 / b : 0
            verdict = ($2 >= floor && b > 0 && change > tol) ? "SLOWER" : "ok"
            if (verdict == "SLOWER") bad++
            printf "%-22s %10s us  baseline %10s us  %+6.0f%%  %s\n", $1, $2, b, change, verdict
        }
        END { if (bad) { printf "%d measurement(s) regressed past %s%%\n", bad, tol; exit 1 } }
    ' "$baseline" "$out"
}
# A shared machine has one-off spikes; a real regression shows on every run.
for attempt in 1 2 3; do
    if compare > build/pic/bench-compare.txt; then
        cat build/pic/bench-compare.txt
        exit 0
    fi
    [ "$attempt" -lt 3 ] || break
    printf 'bench: attempt %s regressed (%s); measuring again\n' "$attempt" \
        "$(grep -c SLOWER build/pic/bench-compare.txt) slower" >&2
    "$bench" "$pic" "${PIC_BENCH_SCALE:-1}" > "$out"
done
cat build/pic/bench-compare.txt
exit 1
