从 C 程序获取 CPU 利用率统计信息

0xF*_*xFF 10 cpu c monitoring top

我想从 C 程序中读取 CPU 利用率统计信息,我对 CPU 使用率、窃取时间等感兴趣。这些统计信息显示在top命令的第三行。

我试图topawk( top -n 1 -b | awk '{print $0}')解析's 的输出,但它似乎top在开始显示正确的统计数据之前总是给出相同的“虚构”值。

有没有办法从代码中,或者通过解析一些命令的输出来获取 CPU 利用率统计信息?

编辑:

平台为Linux

谢谢你。

Dav*_*rtz 7

您想阅读/proc/stat. 您需要阅读两次,间隔一段测量时间,然后从第二组数字中减去第一组数字。这些行看起来像这样:

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 ...
Run Code Online (Sandbox Code Playgroud)

第一行是所有内核的聚合。接下来的几行显示了每个核心。当您看到以 开头的行时intr,您就知道要停止解析了。

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.


Sté*_*nez 3

网上有一些示例/proc/pid/stat展示了如何用C 语言进行读取。

您可以在两个不同时刻读取utimestime值并计算所需的 CPU 利用率统计数据。(我想top也使用这个原始数据。)

(我忘了:这是 Linux 特有的。)