Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I want to read the CPU utilization stats from a C program, I am interested in the percentage of use of CPU, steal time etc. These stats are shown in the 3rd row from the top command.

I tried to parse top 's output with awk (top -n 1 -b | awk '{print $0}'), but it seems that top gives always the same 'fictional' values before it starts showing correct stats.

Is there a way from code, or by parsing some command's output to get the CPU utilization stats?

Edit:

The platform is Linux

Thank you.

share|improve this question
    
Sure, but there is no standard way. Precise the target OS(es). –  jlliagre Sep 27 '11 at 20:44

2 Answers 2

You want to read the first few lines of /proc/stat. You'll need to read it twice, a measured time apart, and subtract the first set of numbers from the second. The lines look like this:

cpu  1526724 408013 600675 541100340 2861417 528 14531 0 0 0
cpu0 344507 77818 251244 134816146 1119991 324 13283 0 0 0
cpu1 502614 324065 179301 133991407 1631824 136 906 0 0 0
cpu2 299080 3527 79456 136144067 103208 59 255 0 0 0
cpu3 380521 2602 90672 136148719 6393 7 86 0 0 0
intr 2111239193 344878476 16943 ...

The first line is aggregate for all cores. The next lines show each core. When you see the line that start with intr, you know to stop parsing.

Each number is the amount of time the CPU has spent in a particular state. The units are typically hundredths of a second. The fields are user, nice, system, idle, iowait, irq, softirq, steal, guest, and guest_nice.

The authoritative documentation is, of course, the source code. If you have a copy of the Linux kernel source handy, look at fs/proc/stat.c, particularly the show_stat function.

share|improve this answer
    
Do you know at what frequency the proc/stat is being updated? like once every 1ms or something, thank you. –  0xFF Sep 29 '11 at 20:19
    
They're not real files. Their contents are calculated when you open them. –  David Schwartz Sep 30 '11 at 0:13

There is some example on the web that shows how to read /proc/pid/stat in C.

You could read utime or stime values at two distinct moments and compute the desired cpu utilization stats. (I guess top uses this raw data too.)

(I forgot: this is linux specific.)

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.