#!/usr/bin/env bash
# Measure CPU% and RSS of nginx vs veld under identical load.
# Usage: resource.sh [duration] [file]
set -u
DUR="${1:-20}"
FILE="${2:-10k.txt}"
BENCH=/tmp/bench
RN_BIN="${RN_BIN:-$HOME/veld/target/release/veld}"
HZ=$(getconf CLK_TCK)
# Sum VmRSS (KB) over all processes whose comm == $1.
sum_rss() {
local t=0 r
for pid in $(pgrep -x "$1"); do
r=$(awk '/^VmRSS:/{print $2}' "/proc/$pid/status" 2>/dev/null)
[ -n "$r" ] && t=$((t + r))
done
echo "$t"
}
# Sum utime+stime jiffies over all processes whose comm == $1.
# Robust to spaces/parens in comm: strip up to the final ") ".
sum_jiffies() {
local t=0 line rest u s
for pid in $(pgrep -x "$1"); do
line=$(cat "/proc/$pid/stat" 2>/dev/null) || continue
rest=${line#*) }
u=$(echo "$rest" | awk '{print $12}') # field 14 overall = utime
s=$(echo "$rest" | awk '{print $13}') # field 15 overall = stime
[ -n "$u" ] && t=$((t + u + s))
done
echo "$t"
}
measure() {
local name="$1" comm="$2" port="$3"
local idle peak j0 j1 w0 w1 cpu rps lat
idle=$(sum_rss "$comm")
wrk -t4 -c100 -d"${DUR}s" --latency "http://127.0.0.1:${port}/${FILE}" >"/tmp/_wrk_${name}.txt" 2>/dev/null &
local wpid=$!
sleep 2 # let it ramp
j0=$(sum_jiffies "$comm"); w0=$(date +%s%N)
peak=0
while kill -0 "$wpid" 2>/dev/null; do
local cur; cur=$(sum_rss "$comm")
[ "$cur" -gt "$peak" ] && peak=$cur
sleep 0.5
done
j1=$(sum_jiffies "$comm"); w1=$(date +%s%N)
wait "$wpid"
cpu=$(awk "BEGIN{printf \"%.0f\", (($j1-$j0)/$HZ)/(($w1-$w0)/1e9)*100}")
rps=$(awk '/Requests\/sec/{print $2}' "/tmp/_wrk_${name}.txt")
lat=$(awk '/99%/{print $2; exit}' "/tmp/_wrk_${name}.txt")
local eff
eff=$(awk "BEGIN{printf \"%.1f\", $cpu/($rps/1000)}")
printf "%-11s idle=%6dKB peak=%7dKB cpu=%4s%% p99=%-8s rps=%-10s cpu_per_kreq=%s\n" \
"$name" "$idle" "$peak" "$cpu" "$lat" "$rps" "$eff"
}
pkill -f veld 2>/dev/null; sleep 1
"$RN_BIN" -c "$BENCH/veld.conf" --prefix "$BENCH" start >"$BENCH/logs/rn.log" 2>&1 &
sleep 2
echo "=== Resource usage under load: c=100, ${DUR}s, file=${FILE} ==="
measure nginx nginx 8080
measure veld veld 8081
echo "--- binary size ---"
echo "nginx: $(stat -c %s "$(command -v nginx)") bytes"
echo "rust : $(stat -c %s "$RN_BIN") bytes"
pkill -f veld 2>/dev/null