栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

您需要从中解析出数据

/proc/<PID>/stat
。这些是前几个字段(来自
documentation/filesystems/proc.txt
内核源代码):

Table 1-3: Contents of the stat files (as of 2.6.22-rc3).............................................................................. Field          Content  pidprocess 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  sidsession 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);

合理?



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/403039.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号