猿问

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

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

我想以编程的方式(在C中)计算Linux中给定进程ID的CPU使用率%。

如何获得给定进程的实时CPU使用率%?

为了进一步明确:

  • 我应该能够确定所提供的proessid或进程的CPU使用情况。
  • 这个过程不一定是子进程。
  • 我想要C语言的解决方案。


喵喔喔
浏览 888回答 3
3回答

精慕HU

您需要从/proc/<PID>/stat..这些是最初的几个字段Documentation/filesystems/proc.txt在您的内核源代码中):Table 1-3: Contents of the stat files (as of 2.6.22-rc3)..............................................................................&nbsp;Field&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Content&nbsp; pid&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;process id&nbsp; tcomm&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;filename of the executable&nbsp; state&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;state (R is running, S is sleeping, D is sleeping in an&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; uninterruptible wait, Z is zombie, T is traced or stopped)&nbsp; ppid&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; process id of the parent process&nbsp; pgrp&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pgrp of the process&nbsp; sid&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;session id&nbsp; tty_nr&nbsp; &nbsp; &nbsp; &nbsp; tty the process uses&nbsp; tty_pgrp&nbsp; &nbsp; &nbsp; pgrp of the tty&nbsp; flags&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;task flags&nbsp; min_flt&nbsp; &nbsp; &nbsp; &nbsp;number of minor faults&nbsp; cmin_flt&nbsp; &nbsp; &nbsp; number of minor faults with child's&nbsp; maj_flt&nbsp; &nbsp; &nbsp; &nbsp;number of major faults&nbsp; cmaj_flt&nbsp; &nbsp; &nbsp; number of major faults with child's&nbsp; utime&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;user mode jiffies&nbsp; stime&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;kernel mode jiffies&nbsp; cutime&nbsp; &nbsp; &nbsp; &nbsp; user mode jiffies with child's&nbsp; cstime&nbsp; &nbsp; &nbsp; &nbsp; kernel mode jiffies with child's你可能是在找utime和/或stime..您还需要阅读cpu从/proc/stat,看起来是:cpu&nbsp;&nbsp;192369&nbsp;7119&nbsp;480152&nbsp;122044337&nbsp;14142&nbsp;9937&nbsp;26747&nbsp;0&nbsp;0这将告诉您在各种类别中使用的累计CPU时间(单位为Jiffies)。您需要取这一行上的值之和,才能获得time_total测量。两者都读utime和stime对于您感兴趣的过程,请阅读time_total从…/proc/stat..然后睡一会儿左右,然后再读一遍。现在,您可以通过以下方法计算采样时间内进程的CPU使用情况:user_util&nbsp;=&nbsp;100&nbsp;*&nbsp;(utime_after&nbsp;-&nbsp;utime_before)&nbsp;/&nbsp;(time_total_after&nbsp;-&nbsp;time_total_before); sys_util&nbsp;=&nbsp;100&nbsp;*&nbsp;(stime_after&nbsp;-&nbsp;stime_before)&nbsp;/&nbsp;(time_total_after&nbsp;-&nbsp;time_total_before);讲得通?

Qyouu

getrage()可以帮助您确定当前进程或其子进程的使用情况。最新情况:我记不起API了。但所有细节将在/proc/PID/stat,所以如果我们能够解析它,我们就可以得到百分比。编辑:因为CPU%不是直接计算的,所以这里可以使用抽样方式。在时间点上读取PID的ctime和utime,1秒后再读取相同的值。找出差异,除以百。您将在超过1秒的时间内获得该进程的利用率。(如果有许多处理器,可能会变得更复杂)
随时随地看视频慕课网APP
我要回答