Hi all, recently I had to do some performance tests at work at AdroitLogic and I wanted to monitor CPU usage and memory usage of a process continuously and get that output to a file so that I can use them to analyze more later with graphs and stuff.
So I came up with two shell scripts which use Linux top and free commands to undertake this task for me.
In these scripts I run the top command in a loop and use grep command to only filter out the rest and get the line I need and then do some text processing using cut and tr. After that result of appended to a file using tee command. Here I am monitoring influxd, a time series database process. You can monitor any process you require by simply replacing the relevant name here “grep -w influxd”. Note that the filter string you use should properly filter out others and only leave a single line.
Hope these will be useful. Cheers!
#!/bin/bash PRG="$0" PRGDIR=`dirname "$PRG"` [ -z "$LT_HOME" ] && LT_HOME=`cd "$PRGDIR/.." ; pwd` cd $LT_HOME rm -rf data/cpu* > data/cpu.csv echo "writing to cpu.csv" echo "TIME_STAMP, Usage%" | tee -a data/cpu.csv while : do DATE=`date +"%H:%M:%S:%s%:z"` echo -n "$DATE, " | tee -a data/cpu.csv top -b -n 1| grep -w influxd | tr -s ' ' | cut -d ' ' -f 10 | tee -a data/cpu.csv sleep 1 done
#!/bin/bash #run with sudo because python script requires sudo permission PRG="$0" PRGDIR=`dirname "$PRG"` [ -z "$LT_HOME" ] && LT_HOME=`cd "$PRGDIR/.." ; pwd` cd $LT_HOME rm -rf data/mem* > data/mem.csv echo "writing to mem.csv" echo "TIME_STAMP,Memory Usage (MB)" | tee -a data/mem.csv total="$(free -m | grep Mem | tr -s ' ' | cut -d ' ' -f 2)" #echo $total while : do DATE=`date +"%H:%M:%S:%s%:z"` echo -n "$DATE, " | tee -a data/mem.csv var="$(top -b -n 1| grep -w influxd | tr -s ' ' | cut -d ' ' -f 11)" echo "scale=3; ($var*$total/100)" | bc | tee -a data/mem.csv sleep 1 done