我想以编程方式 [在 C 中] 计算 Linux 中给定进程 ID 的 CPU 使用率。
我们如何获得给定进程的实时 CPU 使用百分比?
为了更清楚:
最佳答案
您需要解析出 /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
测量。
同时阅读 utime
和 stime
对于您感兴趣的过程,请阅读 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/