在Linux中获取CPU负载的C API

在Linux中,是否有一个内置的C库函数来获取机器的CPU负载? 大概我可以编写自己的函数来打开/parsing/ proc中的文件,但似乎应该有更好的方法。

  • 不需要是便携式的
  • 除了基本的RHEL4安装之外,不需要任何库。

如果你真的想交流接口使用getloadavg() ,这也适用于没有/proc unix。

它有一个包含所有细节的手册页 。

在linux上获取CPU负载信息的首选方法是读取/ proc / stat/ proc / loadavg/ proc / uptime 。 像top这样的所有普通的linux工具都使用这种方法。

从proc(5)手册页:

  /proc/loadavg The first three fields in this file are load average figures giving the number of jobs in the run queue (state R) or waiting for disk I/O (state D) averaged over 1, 5, and 15 minutes. They are the same as the load average numbers given by uptime(1) and other programs. The fourth field consists of two numbers sepaâ rated by a slash (/). The first of these is the number of curâ rently executing kernel scheduling entities (processes, threads); this will be less than or equal to the number of CPUs. The value after the slash is the number of kernel scheduling entities that currently exist on the system. The fifth field is the PID of the process that was most recently created on the system. 

我的理解是,解析/ proc的包含是这种事情的官方接口(在提交给用户之前,有很多文件是真正意图解析的)。

“平均负载”可能不是很有用。 我们发现它的使用有限,因为它实际上并没有告诉你正在使用多少CPU,而只是平均“准备运行”的任务数量。 “准备运行”有点主观,但不是很有帮助,因为它通常包括等待IO的进程。

在繁忙的系统上,我们看到只有8个内核的机器的平均负载为20+,而CPU仍然相对闲置。

如果您想查看正在使用的CPU,请查看/ proc中的各种文件