我想以编程方式[用C]计算Linux中给定进程ID的CPU使用率%.
如何获得给定进程的实时CPU使用率%?
为了进一步说明这一点:
- 我应该能够确定所提供的进程ID或进程的CPU使用率.
- 流程不必是子流程.
- 我想要"C"语言的解决方案.
我想以编程方式[用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
岁了.您还需要读取/proc/stat
中的cpu
行,如下所示:
cpu 192369 7119 480152 122044337 14142 9937 26747 0 0
它以Jiffie为单位告诉您在各种类别中使用的累计CPU时间.你需要把这条线上的值相加,才能得到time_total
的测量值.
对于您感兴趣的流程,请同时阅读utime
和stime
,并从/proc/stat
开始阅读time_total
.然后睡上一秒钟左右,然后把它们再读一遍.现在,您可以使用以下命令计算采样时间内进程的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);
讲得通?