I'm trying to write a little script that, among other things, calculates the cpu usage by reading /proc/stat
, and I can't seem to get consistent results. I'm basically doing a
grep cpu /proc/stat
and then processing the first line that is supposed to accumulate data from all the threads. In my case I've got 4 cores/8 threads. I've also written a program that constantly occupies one thread just to test stuff (it's basically a while(1) { 1 }
). In this context if I'm doing nothing else I would expect 12.5% cpu usage, and if I run top
, I get that:
%Cpu(s): 12,7 usuario, 0,1 sist, 0,0 adecuado, 87,1 inact, 0,1 en espera, 0,
(sorry that it's in another language). The first line of /proc/stat
, though, is as follows:
cpu 1490042 169968 416799 32056116 21179 0 19504 0 0 0
And if I calculate the percentage from here:
(1490042 + 169968 + 416799)/(1490042 + 169968 + 416799 + 32056116) = 6%
Why the inconsistency? I guess I'm not interpreting /proc/stat
properly?