Shell Script – How to Receive Top-Like CPU Statistics

cpuhtopshell-scripttop

I'm trying to get an accurate read of my used CPU (in percent) from top. This is the command I'm running for testing:

top -n1 | awk '/Cpu\(s\):/ {print $2}'

This returns:

10.7%us,

Which is the proper piece of data I want. However, every time I run the command I get the same output, even though I am applying different loads on my system (and not to mention htop tells me my usage is different). It seems that whenever I start top, my CPU usage is the same. Only after a couple of frames does it give me proper values.

It doesn't seem like I can parse top's output this way, so I'm looking for other reliable applications which will give me an accurate reading from the shell. I really like how htop can give me a per-core reading.

I've tried iostat and mpstat but they seem to give inaccurate and "slow to change" values.

Best Answer

I use this script (from this thread on the Arch boards):

#!/bin/bash
read cpu a b c previdle rest < /proc/stat
prevtotal=$((a+b+c+previdle))
sleep 0.5
read cpu a b c idle rest < /proc/stat
total=$((a+b+c+idle))
CPU=$((100*( (total-prevtotal) - (idle-previdle) ) / (total-prevtotal) ))
Related Question