bash
#!/bin/bash
# perf-harness.sh - Baseline Performance Harness
# Usage:
# ./perf-harness.sh init # Initialize baseline (first run)
# ./perf-harness.sh run # Run benchmarks, check budgets/regressions
# ./perf-harness.sh profile # Generate CPU profile
# ./perf-harness.sh clean # Remove artifacts
set -euo pipefail
HARNESS_DIR="$(dirname "$(realpath "$0")")"
BASELINE_FILE="$HARNESS_DIR/baseline.json"
PROFILES_DIR="$HARNESS_DIR/profiles"
BUDGETS_FILE="$HARNESS_DIR/budgets.json"
RESULTS_FILE="$HARNESS_DIR/results.json"
N_ITER=100 # Iterations per benchmark
REGRESSION_THRESHOLD=0.05 # 5% slowdown = regression
mkdir -p "$PROFILES_DIR"
# Sample budgets (edit budgets.json for your metrics)
cat > "$BUDGETS_FILE" << 'EOF'
{
"fib": { "maxTimeMs": 10, "maxMemoryMB": 50 },
"sort": { "maxTimeMs": 5, "maxMemoryMB": 30 },
"matrixMul": { "maxTimeMs": 20, "maxMemoryMB": 100 }
}
EOF
# Node.js benchmark script (benchmarks.js)
cat > "$HARNESS_DIR/benchmarks.js" << 'EOF'
const { performance, monitorEventLoopDelay } = require('perf_hooks');
// Benchmark functions (customize these for your app)
function fib(n) {
if (n <= 1) return n;
return fib(n-1) + fib(n-2);
}
function sortArray() {
const arr = Array.from({length: 10000}, () => Math.random());
arr.sort((a, b) => a - b);
}
function matrixMul() {
const size = 100;
let a = Array(size).fill().map(() => Array(size).fill(0).map(() => Math.random()));
let b = Array(size).fill().map(() => Array(size).fill(0).map(() => Math.random()));
let c = Array(size).fill().map(() => Array(size).fill(0));
for (let i = 0; i < size; i++) {
for (let j = 0; j < size; j++) {
for (let k = 0; k < size; k++) {
c[i][j] += a[i][k] * b[k][j];
}
}
}
}
const benchmarks = [
{ name: 'fib', fn: () => fib(35) },
{ name: 'sort', fn: sortArray },
{ name: 'matrixMul', fn: matrixMul }
];
function runBenchmark(bench, iterations) {
const startTime = performance.now();
const startMem = process.memoryUsage().heapUsed;
let eventLoopDelays = [];
for (let i = 0; i < iterations; i++) {
bench.fn();
// Sample event loop delay
if (i % 10 === 0) {
eventLoopDelays.push(monitorEventLoopDelay().toString() * 1000);
}
}
const endTime = performance.now();
const endMem = process.memoryUsage().heapUsed;
const avgELD = eventLoopDelays.length ? eventLoopDelays.reduce((a, b) => a + parseFloat(b), 0) / eventLoopDelays.length : 0;
return {
name: bench.name,
timeMs: (endTime - startTime) / iterations,
memoryMB: Math.round((endMem - startMem) / 1024 / 1024 * 100) / 100,
eventLoopDelayMs: avgELD
};
}
if (require.main === module) {
const results = benchmarks.map(b => runBenchmark(b, process.argv[2] || 100));
console.log(JSON.stringify(results, null, 2));
}
EOF
run_benchmarks() {
node "$HARNESS_DIR/benchmarks.js" "$N_ITER" > "$RESULTS_FILE"
}
load_json() {
jq -c '.' "$1" 2>/dev/null || echo "{}"
}
save_baseline() {
cp "$RESULTS_FILE" "$BASELINE_FILE"
echo "✓ Baseline saved: $BASELINE_FILE"
}
check_budgets() {
local budgets=$(load_json "$BUDGETS_FILE")
local results=$(load_json "$RESULTS_FILE")
echo "📊 Checking budgets..."
local failed=0
results | jq -r '.[] | .name as $name | .timeMs as $time | .memoryMB as $mem | "\($name): \($time|floor)ms / \($mem)MB"' >&2
results | jq -s '.[0] as $res | $budgets | to_entries[] | select(.key == $res[].name) | .value as $budget |
if ($res[] | select(.name == .key) | .timeMs > $budget.maxTimeMs or .memoryMB > $budget.maxMemoryMB) then empty else "FAIL: \(.key)" end' |
while read line; do
echo "❌ Budget $line" >&2
failed=1
done
[ $failed -eq 0 ] && echo "✓ All budgets passed" || (echo "💥 Budgets failed" >&2 && exit 1)
}
check_regressions() {
if [ ! -f "$BASELINE_FILE" ]; then
echo "⚠ No baseline found. Run 'init' first."
return 1
fi
local baseline=$(load_json "$BASELINE_FILE")
local results=$(load_json "$RESULTS_FILE")
echo "🔍 Checking regressions (threshold: ${REGRESSION_THRESHOLD*100}%)..."
local regressed=0
results | jq -s '.[1] as $res | .[0] as $base | $res[] | .name as $name |
($base[] | select(.name == $name).timeMs) as $baseTime |
if (.timeMs > $baseTime * (1 + '"$REGRESSION_THRESHOLD"')) then
"REGRESSION: \($name): \(.timeMs|floor)ms (+ \(((.) - $baseTime)/$baseTime*100|tostring)+"%"")"
else empty end' --argjson base "$baseline" --argjson res "$results" |
while read line; do
echo "📉 $line" >&2
regressed=1
done
[ $regressed -eq 0 ] && echo "✓ No regressions detected" || (echo "💥 Regressions detected" >&2 && exit 1)
}
case "${1:-}" in
init)
echo "🏁 Initializing baseline..."
run_benchmarks
save_baseline
check_budgets
;;
run)
echo "🚀 Running benchmarks..."
run_benchmarks
check_budgets
check_regressions
;;
profile)
echo "🔥 Generating CPU profile (v8-profiler)..."
mkdir -p "$PROFILES_DIR/$(date +%Y%m%d-%H%M%S)"
node --prof "$HARNESS_DIR/benchmarks.js" "$N_ITER" > /dev/null
mv isolate-*.log "$PROFILES_DIR/$(date +%Y%m%d-%H%M%S)/"
echo "Profiles saved to $PROFILES_DIR. Use 'node --prof-process isolate-*.log > profile.txt' to process."
;;
clean)
rm -f "$BASELINE_FILE" "$RESULTS_FILE" "$BUDGETS_FILE" "$HARNESS_DIR/benchmarks.js"
rm -rf "$PROFILES_DIR"
echo "🧹 Cleaned."
;;
*)
cat << EOF
Baseline Perf Harness: Profiles, Budgets, Regressions
Commands:
init - Run benchmarks, save baseline.json
run - Run + check budgets/regressions
profile - Generate V8 CPU profiles (--prof)
clean - Remove artifacts
Metrics: timeMs (avg), memoryMB (delta), eventLoopDelayMs
Customize: benchmarks.js, budgets.json
Requires: Node.js, jq (brew install jq)
EOF
exit 1
;;
esac