小编典典
您需要从中解析出数据/proc//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时间。您需要对这条线上的值求和才能得到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);
合理?
2020-06-02