Skip to content

Instantly share code, notes, and snippets.

@jsfaint
Created April 12, 2017 10:07
Show Gist options
  • Save jsfaint/02139eff5665dcb666365c99a3c90217 to your computer and use it in GitHub Desktop.
Save jsfaint/02139eff5665dcb666365c99a3c90217 to your computer and use it in GitHub Desktop.
Monitor the memory usage of given process
#!/bin/bash
# Configure by yourself
procname="cagent"
duration=10
usage()
{
echo "$0 {process name} {duration}"
echo "By default:"
echo " process name is 'cagent'"
echo " duration is '10' sencods"
}
# Parse parameters
[ ! -z "$1" ] && procname="$1"
[ ! -z "$2" ] && duration="$2"
now=$(date +%Y%m%d%H%M%S)
outputfile="mem_for_${procname}_${now}.csv"
# Print usage
[ "-h" == "$procname" ] && usage && exit 1
# CPU cores
cpu_cores="$(($(grep -w processor /proc/cpuinfo | tail -n 1 | awk '{print $3}') + 1))"
{
echo "CPU Cores,$cpu_cores,,"
echo ",,,"
} >> "$outputfile"
echo "Date,Pid,VmSize(KB),CPU%" >> "$outputfile"
while true; do
# Get pid
pid_list=$(pgrep "$procname")
[ -z "$pid_list" ] && echo "PID is null" && exit 1
#get VMsize
for pid in $pid_list; do
echo -n "$(date +"%Y-%m-%d %H:%M:%S"), " >> "$outputfile"
echo -n "$pid," >> "$outputfile"
mem=$(grep VmSize "/proc/$pid/status")
mem2=$(echo "$mem" | grep -o '[0-9]\+')
echo -n "$mem2," >> "$outputfile"
#get the pid CPU Usage
cpu=$(top -n 1 -p "$pid" | tail -2 | head -1 | awk '{ssd=NF-4} {print $ssd}')
echo "$cpu," >> "$outputfile"
done
sleep "$duration"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment