Stéphane
Stéphane

Reputation: 20340

How do I get per-cpu stats (system, idle, nice, ...) like the "top" command does?

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.

Upvotes: 8

Views: 9406

Answers (3)

manav m-n
manav m-n

Reputation: 11394

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);
    }
}

Upvotes: 0

Matthew Slattery
Matthew Slattery

Reputation: 46998

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

Upvotes: 6

mtvec
mtvec

Reputation: 18316

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

Upvotes: 2

Related Questions