为了账号安全,请及时绑定邮箱和手机立即绑定

如何用C语言在Linux中用PID计算进程的CPU使用量?

如何用C语言在Linux中用PID计算进程的CPU使用量?

喵喔喔 2019-07-22 15:56:02
如何用C语言在Linux中用PID计算进程的CPU使用量?我想以编程的方式(在C中)计算Linux中给定进程ID的CPU使用率%。如何获得给定进程的实时CPU使用率%?为了进一步明确:我应该能够确定所提供的proessid或进程的CPU使用情况。这个过程不一定是子进程。我想要C语言的解决方案。
查看完整描述

3 回答

?
精慕HU

TA贡献1845条经验 获得超8个赞

您需要从/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测量。

两者都读utimestime对于您感兴趣的过程,请阅读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);

讲得通?


查看完整回答
反对 回复 2019-07-22
?
Qyouu

TA贡献1786条经验 获得超11个赞

getrage()可以帮助您确定当前进程或其子进程的使用情况。

最新情况:我记不起API了。但所有细节将在/proc/PID/stat,所以如果我们能够解析它,我们就可以得到百分比。

编辑:因为CPU%不是直接计算的,所以这里可以使用抽样方式。在时间点上读取PID的ctime和utime,1秒后再读取相同的值。找出差异,除以百。您将在超过1秒的时间内获得该进程的利用率。

(如果有许多处理器,可能会变得更复杂)


查看完整回答
反对 回复 2019-07-22
  • 3 回答
  • 0 关注
  • 860 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信