Script bases on the top command
The unix top command in can be used in scripts. The -b allows to start the batch mode, and it will refresh the output number of times provided with the -n option or the top process will be killed. For example, top -b -n 2 will execute it in two iterations.
Keeping in mind above, I am able to write a simple script to monitor the usage of the CPU every second.
#!/bin/bash
CPU_STR="^%CPU:"
while true; do
d=$(date +%Y%m%d_%H%M%S)
c=$(top -b -n 1 | grep $CPU_STR | xargs | tr -d "$CPU_STR ")
echo "$d $c"; sleep 0.5
done
Note: Various versions of top returns the CPU string in different
ways. For Debian-based system it is %CPU, and the %Cpu(s) for
RedHat-based ones. Change CPU_STR variable to adjust to your system.
Reference:
There is an RSS feed for this blog.