linux c获取进程的cpu使用率,如何用C在Linux中通过PID计算进程的CPU使用率?

小编典典

您需要从中解析出数据/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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值