Skip to content

Instantly share code, notes, and snippets.

@joshlk
Last active July 25, 2023 12:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshlk/ebe48cc579f986a50ea6f080e1b912e6 to your computer and use it in GitHub Desktop.
Save joshlk/ebe48cc579f986a50ea6f080e1b912e6 to your computer and use it in GitHub Desktop.
Measure the peak memory of the system while a command is running (this only includes physical memory and not virtual memory)
#!/usr/bin/env bash
# peak_memory [command ...]
# Run the given command line in the background and kill if script exits
trap 'kill $(jobs -p) 2&> /dev/null' EXIT
"$@" &
pid=$! phys_peak=0 not_avail_peak=0
# while command still running
while ps -p $pid &>/dev/null; do
sleep 1
mem_total="$(cat /proc/meminfo | grep 'MemTotal:' | grep -oe '\([0-9.]*\)')"
mem_free="$(cat /proc/meminfo | grep 'MemFree:' | grep -oe '\([0-9.]*\)')"
mem_avail="$(cat /proc/meminfo | grep 'MemAvailable:' | grep -oe '\([0-9.]*\)')"
phys=$(($mem_total - $mem_free))
not_avail=$(($mem_total - $mem_avail))
let phys_peak='phys > phys_peak ? phys : phys_peak'
let not_avail_peak='not_avail > not_avail_peak ? not_avail : not_avail_peak'
done
phys_peak=$(($phys_peak / 1048576))
not_avail_peak=$(($not_avail_peak / 1048576))
printf '%s %s\n' "$(date)" "Peak Used Physical memory: $phys_peak GiB" 1>&2
printf '%s %s\n' "$(date)" "Peak Used Not-Available memory (exc. mmap and cache): $not_avail_peak GiB" 1>&2
@joshlk
Copy link
Author

joshlk commented Jul 25, 2023

Example output:

$ peak_memory sleep 2	
Fri Dec  2 14:46:08 GMT 2022 Peak Used Physical memory: 140 GiB	
Fri Dec  2 14:46:08 GMT 2022 Peak Used Not-Available memory (exc. mmap and cache): 17 GiB

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment