Reading per-core CPU usage from the command line
Saturday December 17th, 2011
I’ve recently started using dwm, a very modular titling window manager (instead of the native KDE OpenSuse shipped with). The level of customization available with the thing is amazing. A neat feature is the ability to set custom output on the status bar on the top of the screen, which is perfect for displaying live statistics of your system. I’ll be posting a couple useful code snippets that can be put in your ~/.xinitrc file so that it is run when X starts.
This snippet will show you how to get accurate CPU usage (in percentage) from any core in your system. It works equally well for single core computers. If you’re monitoring multiple cores (6+) there might be a small amount of lag in data acquisition, seeing as we will be parsing data sequentially and not in parallel.
This is a modification of a script from the Arch boards. Thanks to Procyon for that. Place the following code in your ~/.xinitrc file, near the end but before invoking the window manager:
while true; do
read cpu0 a0 b0 c0 previdle0 rest < /proc/stat
read cpu1 a1 b1 c1 previdle1 rest < /proc/stat
prevtotal0=$((a0+b0+c0+previdle0))
prevtotal1=$((a1+b1+c1+previdle1))
sleep 0.5
read cpu0 a0 b0 c0 idle0 rest < /proc/stat
read cpu1 a1 b1 c1 idle1 rest < /proc/stat
total0=$((a0+b0+c0+idle0))
total1=$((a1+b1+c1+idle1))
CPU0=$((100*( (total0-prevtotal0) - (idle0-previdle0) ) / (total0-prevtotal0) ))
CPU1=$((100*( (total1-prevtotal1) - (idle1-previdle1) ) / (total1-prevtotal1) ))
CPU="[CPU0 "$CPU0"] [CPU1"$CPU1"]"
xsetroot -name $CPU
done &
The basic idea here is that we first read the line in /proc/stat corresponding to the core we want to evaluate. This is done once for each core. Then we calculate the total usage for each of the cores. A brief moment later (half a second to be precise) we perform the same calculations, giving us two distinct points of data about our CPU.
The last step is converting our data points to a percentage, and passing the string to the xsetroot utility. xsetroot is used by dwm to write directly to the status bar. One last important note is the ampersand (&) at the end of the while loop in the script. It allows X to run the loop in the background while the window manager is started up.



