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

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

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

为了更清楚:

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

最佳答案

您需要解析出 /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 .您还需要阅读 cpu来自 /proc/stat 的行,看起来像:

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);

有意义吗?

https://stackoverflow.com/questions/1420426/

相关文章:

linux - 工控机性能: Named Pipe vs Socket

python - 移动平均线或移动平均线

python - Python 3 的图像库

python - 如何获取项目在列表中的位置?

linux - 是否可以在文件名中使用 "/"?

linux - 在linux中用制表符替换空格

linux - POSIX 异步 I/O (AIO) 的现状如何?

python - 转置一维 NumPy 数组

python - 是否可以使用 scikit-learn K-Means Clustering 指定

python - Pelican 3.3 pelican-quickstart 错误 "ValueE