[nylug-talk] Getting CPU utilization programmatically

Frank D. Greco
Thu Aug 31 23:26:34 EDT 2006


I'm building a Java probe that gives me the CPU utilization of a given machine.

I read some info on /proc/stat so I think I'm on the right track.  I 
just need a little confirmation on my assumptions.

Here's what I know or assume:

   CPU utilization is time spent doing useful stuff, i.e., 100 - idle time.
   The first line of /proc/stat gives me aggregate user/system/nice/idle
     counters.

My proposed plan:

   Take a snapshot of all 4 counters (array "snap1")
     now sleep for a time
   Take another snapshot of all 4 counters (array "snap2")
   Take the differences of each element of snap2 with snap1
     i.e., for i = 0 to 4, diff[i] = snap2[i] - snap1[i]
   Now total up the elements in this diff array
   Idle% is Idle time (the 4th element) divided by the total

   CPU% is then 100 - Idle%


I seem to be getting reasonable numbers this way, but
they don't seem to jive with the output of mpstat (looking
at idle% there).

Anyone see a flaw in my algorithm?

Thanks,

Frank G.
--
+==============================================+
| Crossroads Technologies Inc.                 |
| www.CrossroadsTech dot com                   |
| fgreco at REMOVEtheX!cross!roads!tech!dotXcom|
+==============================================+
--



More information about the nylug-talk mailing list