1

I want to get a decently accurate value for overall cpu utilization at 1 sec granularity, while introducing minimal delay possible.

I tried "top" but that is not at all accurate because of the delay between cpu dumps.

Right now I am doing it by reading /proc/stat which works fine for 2 sec granularity, however I am not sure if it will work reliably at 1 sec granularity. How frequent is /proc/stat updated ?

Also, any idea how accurate would it be read /proc/loadavg (or calling getloadavg()) would be ? Can it work reliably at 1 sec intervals ?

Any solution that can work on c/c++ should do.

L Lawliet
  • 2,565
  • 4
  • 26
  • 35

2 Answers2

2

Complex considerations aside, a single CPU is either active or not.

During a timespan, "CPU usage" is how much of that time was spent working, not how hard the work was.

The shorter the timespan you measure, the less the measurement makes sense. If you had a granularity of 1 nanosecond, you'd always find CPU usage at 100% or 0%.

2 seconds is a decent timespan. More, and you'd miss important spikes; less, and everything would be a spike.

salezica
  • 74,081
  • 25
  • 105
  • 166
  • Yes but the question is whether 1 seconds granularity is really that small still with faster hardware ? This was the reason I decided to go for 2 sec around 3-4 years ago... Since then cpus and kernel seems to be much more evolved. – L Lawliet Aug 21 '14 at 20:28
  • I don't think faster hardware matters. Remember: CPU usage is not _how hard_, but _how frequent_. What matters is how often processes switch from blocking to actively computing -- process behaviour patterns, if you will. And that hasn't changed much. – salezica Aug 22 '14 at 02:51
1

Have you tried using top with the -d1 argument?

I use it often for testing and it sets the polling interval to 1sec (much faster than the default).

Per the man page for reference:

  -d  :Delay-time interval as:  -d ss.t (secs.tenths)
        Specifies the delay between screen updates, and overrides the
        corresponding value in one's personal configuration  file  or
        the  startup default.  Later this can be changed with the 'd'
        or 's' interactive commands.

        Fractional seconds are honored, but a negative number is  not
        allowed.   In all cases, however, such changes are prohibited
        if top is running in 'Secure mode', except for  root  (unless
        the 's' command-line option was used).  For additional infor‐
        mation on 'Secure mode' see topic  6a.  SYSTEM  Configuration
        File.
Dan
  • 175
  • 2
  • 12
  • please correct me if I am wrong but top is based cpu dumps right? Is it reliably accurate ? I am looking for accuracy at least decently close to that of reading /proc/stat directly. – L Lawliet Aug 21 '14 at 20:36