To get usage percent total since bringing the system up:
awk '/cpu /{print 100*($2+$4)/($2+$4+$5)}' /proc/stat
To get the usage percentage over the last second:
awk -v a="$(awk '/cpu /{print $2+$4,$2+$4+$5}' /proc/stat; sleep 1)" '/cpu /{split(a,b," "); print 100*($2+$4-b[1])/($2+$4+$5-b[2])}' /proc/stat
Explanation
From man 5 proc
, the meaning of the first four numbers on the cpu line in /proc/stat
is given by:
cpu 3357 0 4313 1362393
The amount of time, measured in units of USER_HZ (1/100ths of a second on most architectures, use sysconf(_SC_CLK_TCK)
to obtain the right value), that the system spent
in user mode, user mode with low priority (nice), system mode, and the idle task, respectively. The last value
should be USER_HZ times the second entry in the uptime
pseudo-file.
The get the CPU usage, we add the user and system times and divide by the total of user, system, and idle time.
Let's look again at the calculation for total CPU usage since system up:
awk '/cpu /{print 100*($2+$4)/($2+$4+$5)}' /proc/stat
By requiring that the line match cpu
, we get system totals. The second column is user time, the fourth is system time, and the fifth is idle time. The ratio is multiplied by 100 to get a percentage.
Now, let's consider the recent CPU usage:
awk -v a="$(awk '/cpu /{print $2+$4,$2+$4+$5}' /proc/stat; sleep 1)" '/cpu /{split(a,b," "); print 100*($2+$4-b[1])/($2+$4+$5-b[2])}' /proc/stat
This reads /proc/cpu
twice, a second apart. The first time, the CPU user + system, and user+system+idle times are saved in the variable a
. sleep
is called to delay for a second. Then, /proc/cpu
is read a second time. Tne old user+system total is subtracted from the new total and divided by the change in the total of all times. The result is multiplied by 100 to convert it to percent and printed.