Skip to content

Instantly share code, notes, and snippets.

@ctberthiaume
Last active September 4, 2020 01:09
Show Gist options
  • Save ctberthiaume/73359e8922f6879c86c1e4c1051ddb83 to your computer and use it in GitHub Desktop.
Save ctberthiaume/73359e8922f6879c86c1e4c1051ddb83 to your computer and use it in GitHub Desktop.
Create a timeseries TSV of physical memory usage by command name
#!/bin/sh
if [ $# -ne 2 ]; then
exit;
fi
search=$1
delay=$2
header=0
os=$(uname)
if [ "$os" = "Darwin" ]; then
while true; do
t=
for pid in $(pgrep "$search"); do
if [ $header -eq 0 ]; then
# time = RFC3339 timestamp
# pid = process ID
# physical = current physical memory
# virtual = current virtual memory
# search_term = search term
printf "%s\t%s\t%s\t%s\t%s\n" "time" "pid" "physical" "virtual" "search_term"
header=1
fi
printf "%s\t%s\t%s\t%s\t%s\n" \
$(TZ=UTC date "+%Y-%m-%dT%H:%M:%SZ") \
$(ps -o pid=,rss=,vsz= -p $pid | awk 'BEGIN {OFS=" "} {$1=$1; print}' 2>/dev/null) \
"$search"
done
sleep "$delay"
done
elif [ "$os" = "Linux" ]; then
while true; do
t=$(TZ=UTC date "+%Y-%m-%dT%H:%M:%SZ")
for pid in $(pgrep "$search"); do
if [ $header -eq 0 ]; then
# time = RFC3339 timestamp
# pid = process ID
# physical = current physical memory
# peak_physical = peak physical memory
# virtual = current virtual memory
# peak_virtual = peak virtual memory
# search_term = search term
# command_line = command line
printf "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n" \
"time" "pid" "physical" "peak_physical" "virtual" "peak_virtual" "search_term" "command_line"
header=1
fi
printf "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n" \
$(TZ=UTC date "+%Y-%m-%dT%H:%M:%SZ") \
$pid \
$(awk 'BEGIN {OFS=" "} /VmRSS|VmHWM|VmSize|VmPeak/ {x[substr($1,1,length($1)-1)] = $2} END {print x["VmRSS"], x["VmHWM"], x["VmSize"], x["VmPeak"]}' /proc/$pid/status 2>/dev/null) \
"$search" \
"$(sed -e "s/\x00/ /g" /proc/$pid/cmdline 2>/dev/null | sed -e "s/ $//")"
done
sleep "$delay"
done
else
echo "OS not supported" 1>&2
exit 1
fi
@ctberthiaume
Copy link
Author

ctberthiaume commented Aug 13, 2020

For example, on Linux, tracking current and peak memory use

$ trackmem.sh bash 3
time	pid	physical	peak_physical	virtual	peak_virtual	search_term	command_line
2020-09-04T01:08:25Z	1	3444	3444	4112	4112	bash	bash
2020-09-04T01:08:28Z	1	3444	3444	4112	4112	bash	bash

On MacOS, only able to track current memory use

$ trackmem.sh bash 3
time	pid	physical	virtual	search_term
2020-09-04T01:07:49Z	21288	504	4296812	bash
2020-09-04T01:07:49Z	58937	404	4296812	bash
2020-09-04T01:07:49Z	78589	712	4296812	bash
2020-09-04T01:07:49Z	98061	1352	4296812	bash
2020-09-04T01:07:49Z	99640	736	4296812	bash
2020-09-04T01:07:52Z	21288	504	4296812	bash
2020-09-04T01:07:52Z	58937	404	4296812	bash
2020-09-04T01:07:52Z	78589	712	4296812	bash
2020-09-04T01:07:53Z	98061	1352	4296812	bash
2020-09-04T01:07:53Z	99640	736	4296812	bash

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