Friday 3 April 2020

Linux script to monitor top ten CPU consuming process

CPU monitoring bash script for an hour

vi cpu_usage.sh
#!/bin/bash
#calculate cpu usage by processes for 1 hour

SECS=3600
UNIT_TIME=60

STEPS=$(( $SECS / $UNIT_TIME ))

echo Watching CPU usage... ;

for ((i=0;i<STEPS;i++))
do
 ps -eocomm,pcpu | tail -n +2 >> /tmp/cpu_usage.$$
 sleep $UNIT_TIME
done

echo
echo CPU eaters :

cat /tmp/cpu_usage.$$ | \
awk '
{ process[$1]+=$2; }
END{
 for(i in process)
 { printf("%-20s%d\n",i, process[i]); }
 }' | sort -nrk 2 | head

rm -rf /tmp/cpu_usage.$$

./cpu_usage.sh
Watching CPU usage...

CPU eaters :
xfs-reclaim/sda      0
xfs-reclaim/dm-     0
xfs_mru_cache       0
xfs-log/sda1           0
xfs-log/dm-0          0
xfs-eofblocks/s       0
xfs-eofblocks/d      0
xfs-data/sda1         0
xfs-data/dm-0        0
xfs-conv/sda1         0

No comments:

Post a Comment