Skip to content

Instantly share code, notes, and snippets.

@scivision
Last active April 13, 2026 02:47
Show Gist options
  • Select an option

  • Save scivision/b09fdc0c938fffd75d5710ea57b92055 to your computer and use it in GitHub Desktop.

Select an option

Save scivision/b09fdc0c938fffd75d5710ea57b92055 to your computer and use it in GitHub Desktop.
Sample maximum memory (RAM) pressure on Linux or macOS
#!/bin/bash
# Process tree memory peak monitor (samples at 10 Hz) for a given command.
# Works on Linux (uses PSS) and macOS (uses RSS)
#
# Usage:
# ./memory_pressure.sh /path/to/executable [arguments...]
#
# Alternative:
# for Linux only, one could use Cgroups v2 to track memory usage of the process tree
if [ $# -eq 0 ]; then
echo "Usage: $0 <command> [args...]"
exit 1
fi
OS="$(uname)"
echo "Starting benchmark on $OS and monitoring memory peak..."
"$@" &
PID=$!
max_mem=0
while kill -0 $PID 2>/dev/null; do
# Get all child PIDs (including the main one)
CHILDREN=$(pgrep -P "$PID" 2>/dev/null | tr '\n' ' ')
PIDS="$PID $CHILDREN"
if [ "$OS" = "Linux" ]; then
# On Linux: use PSS (avoids overcounting shared memory)
current_mb=$(awk '
BEGIN {sum=0}
/Pss:/ {sum += $2}
END {printf "%.1f", sum / 1024}
' /proc/$PIDS/smaps 2>/dev/null || echo 0)
else
# Sum RSS (in KB) for the whole tree and convert to MiB
current_mb=$(ps -o rss= -p $PIDS 2>/dev/null | awk '{sum += $1} END {printf "%.1f", sum / 1024}')
fi
if (( $(echo "$current_mb > $max_mem" | bc -l 2>/dev/null || echo 0) )); then
max_mem=$current_mb
printf "\rNew peak: %6.1f MiB" "$max_mem"
fi
sleep 0.1
# 10 Hz sampling rate to catch short spikes without overwhelming the system
done
echo -e "\n\n=== Benchmark finished ===\nPeak memory usage (RSS) of process tree: ${max_mem} MiB"
#!/bin/bash
# Peak memory usage estimate for top-level process and biggest single child
# not suitable for multiple child processes like "mpiexec" or "python -m torch.distributed.launch"
# Usage:
# ./peak_child.sh /path/to/executable [arguments...]
if [[ "$(uname)" == "Darwin" ]]; then
/usr/bin/time -l "$@" 2>&1 | \
awk '/maximum resident set size/ {printf "Peak RSS: %.1f MiB\n", $1/1024/1024}'
else
/usr/bin/time -v "$@" 2>&1 | \
awk '/Maximum resident set size/ {printf "Peak RSS: %.1f MiB\n", $6/1024}'
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment