0

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?

1

I'll have to answer my question since finding an answer wasn't all that hard, I just misread the documentation on /proc/stat

/proc/stat shows aggregated data since bootup, therefore to calculate average cpu usage during a given time interval, you have to calculate the differences of the values given in /proc/stat at the beginning and end of that time interval.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.