tags:

views:

784

answers:

5

In linux, is there a built-in C library function for getting the CPU load of the machine? Presumably I could write my own function for opening and parsing a file in /proc, but it seems like there ought to be a better way.

  • Doesn't need to be portable
  • Must not require any libraries beyond a base RHEL4 installation.
+1  A: 

My understanding is that parsing the contains of /proc is the official interface for that kind of thing (there are a number of files there which are really meant to be parsed before presented to the user).

AProgrammer
+4  A: 

The preferred method of getting information about CPU load on linux is to read from /proc/stat, /proc/loadavg and /proc/uptime. All the normal linux utilities like top use this method.

indy
+1  A: 

from the proc (5) man page:

   /proc/loadavg
          The  first  three  fields  in this file are load average figures
          giving the number of jobs in the run queue (state R) or  waiting
          for disk I/O (state D) averaged over 1, 5, and 15 minutes.  They
          are the same as the load average numbers given by uptime(1)  and
          other  programs.  The fourth field consists of two numbers sepaâ
          rated by a slash (/).  The first of these is the number of  curâ
          rently   executing   kernel   scheduling   entities  (processes,
          threads); this will be less than or equal to the number of CPUs.
          The  value  after  the  slash is the number of kernel scheduling
          entities that currently exist on the system.  The fifth field is
          the  PID  of  the  process that was most recently created on the
          system.
tr3
+5  A: 

If you really want a c interface use getloadavg(), which also works in unixes without /proc.

It has a man page with all the details.

dmckee
Indeed. All the puffing above about the "unix way" notwithstanding, this really is the portable way to do it. On linux, of course, it's just a library function on top of a /proc read.
Andy Ross
A: 

"Load average" may not be very useful. We find it to be of limited use, as it doesn't actually tell you how much CPU is being used, only the average number of tasks "ready to run". "Ready to run" is somewhat subjective, but not very helpful as it often includes processes waiting for IO.

On busy systems, we see load average of 20+ on machines with only 8 cores, and still the CPUs are relatively idle.

If you want to see what CPU is in use, have a look at the various files in /proc

MarkR