如何从 C 中通过 PID 在 Linux 中计算进程的 CPU 使用率?

新手上路,请多包涵

我想以编程方式 [在 C 中] 计算 Linux 中给定进程 ID 的 CPU 使用率。

我们如何获得给定进程的实时 CPU 使用百分比?

为了进一步明确:

  • 我应该能够确定提供的 processid 或进程的 CPU 使用率。
  • 该进程不必是子进程。
  • 我想要’C’语言的解决方案。

原文由 codingfreak 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 729
2 个回答

您需要从 /proc/<PID>/stat 中解析出数据。这些是前几个字段(来自内核源代码中的 Documentation/filesystems/proc.txt ):

 Table 1-3: Contents of the stat files (as of 2.6.22-rc3)
..............................................................................
 Field          Content
  pid           process id
  tcomm         filename of the executable
  state         state (R is running, S is sleeping, D is sleeping in an
                uninterruptible wait, Z is zombie, T is traced or stopped)
  ppid          process id of the parent process
  pgrp          pgrp of the process
  sid           session id
  tty_nr        tty the process uses
  tty_pgrp      pgrp of the tty
  flags         task flags
  min_flt       number of minor faults
  cmin_flt      number of minor faults with child's
  maj_flt       number of major faults
  cmaj_flt      number of major faults with child's
  utime         user mode jiffies
  stime         kernel mode jiffies
  cutime        user mode jiffies with child's
  cstime        kernel mode jiffies with child's

您可能在 utime 和/或 stime 。您还需要阅读 --- 中的 /proc/stat cpu 行,如下所示:

 cpu  192369 7119 480152 122044337 14142 9937 26747 0 0

这会告诉您在各种类别中使用的累积 CPU 时间,以 jiffies 为单位。您需要取此行上的值的总和以获得 time_total 测量值。

阅读 utimestime 以了解您感兴趣的过程,并阅读 time_total 来自 /proc/stat 然后睡一秒钟左右,然后再读一遍。您现在可以计算采样时间内进程的 CPU 使用率,其中:

 user_util = 100 * (utime_after - utime_before) / (time_total_after - time_total_before);
sys_util = 100 * (stime_after - stime_before) / (time_total_after - time_total_before);

说得通?

原文由 caf 发布,翻译遵循 CC BY-SA 2.5 许可协议

getrusage() 可以帮助您确定当前进程或其子进程的使用情况

更新: 我不记得 API。但是所有细节都在 /proc/ PID /stat 中,所以如果我们可以解析它,我们就可以得到百分比。

编辑: 由于 CPU % 不能直接计算,您可以在这里使用采样类型的东西。在某个时间点读取 PID 的 ctime 和 utime 并在 1 秒后再次读取相同的值。找出差异并除以百。您将在过去一秒钟内获得该过程的利用率。

(如果有很多处理器可能会变得更复杂)

原文由 vpram86 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题