tags:

views:

393

answers:

3

On linux, I'd like to know what "C" API to call to get the per-cpu stats.

I know about and could read /proc/loadavg from within my app, but this is the system-wide load avarages, not the per-cpu information. I want to tell the individual CPUs or cores apart.

As an example of an application that does this, When I run top and press "1", I can see the 4 or 8 processors/cores like this:

Cpu0  :  4.5%us,  0.0%sy,  0.0%ni, 95.5%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st
Cpu1  : 42.2%us,  6.2%sy,  0.5%ni, 51.2%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st
Cpu2  :  3.0%us,  1.5%sy,  0.0%ni, 94.5%id,  0.0%wa,  0.0%hi,  1.0%si,  0.0%st
Cpu3  :  7.0%us,  4.7%sy,  0.0%ni, 88.3%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st

I've tried to strace top but this led to a rat's nest.

+1  A: 

This is not a real answer but I would take a look at the source code of top.

Job
The source code for top can be found here: http://sourceforge.net/projects/unixtop/
jschmier
A: 

I guess kernel file timer.c may be of some importance in this scenario to calculate load averages. From the file timer.c function calc_load()

unsigned long avenrun[3];

static inline void calc_load(unsigned long ticks) {

  unsigned long active_tasks; /* fixed-point */
  static int count = LOAD_FREQ;

  count -= ticks;
  if (count < 0) {
     count += LOAD_FREQ;
     active_tasks = count_active_tasks();
     CALC_LOAD(avenrun[0], EXP_1, active_tasks);
     CALC_LOAD(avenrun[1], EXP_5, active_tasks);
     CALC_LOAD(avenrun[2], EXP_15, active_tasks);
  }    

}

Manav MN
+4  A: 

The file you want is /proc/stat. (You might want to refer to fs/proc/stat.c in the Linux kernel source.)

Matthew Slattery
Exactly what I was looking for! Thank you.
Stéphane