Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

linux

cpu-usage

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.

like image 695
Stéphane Avatar asked Jan 23 '10 10:01

Stéphane


2 Answers

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

like image 104
Matthew Slattery Avatar answered Sep 28 '22 03:09

Matthew Slattery


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

like image 25
mtvec Avatar answered Sep 28 '22 02:09

mtvec