gpt4 book ai didi

linux - 如何从/proc/pid/stat 获取应用程序的总 CPU 使用率?

转载 作者:IT老高 更新时间:2023-10-28 12:33:47 33 4
gpt4 key购买 nike

我想知道如何计算一个进程的总 CPU 使用率。

如果我这样做 cat /proc/<em>pid</em>/stat ,我认为相关领域是(taken from lindevdoc.org):

  1. 在用户代码中花费的 CPU 时间,以 jiffies 为单位衡量
  2. 在内核代码中花费的 CPU 时间,以 jiffies 为单位衡量
  3. 在用户代码中花费的 CPU 时间,包括来自 child 的时间
  4. 在内核代码中花费的 CPU 时间,包括来自子代的时间

那么总时间是花费在字段 14 到 17 的总和上吗?

最佳答案

准备

要计算特定进程的 CPU 使用率,您需要以下内容:

  1. /proc/uptime
    • #1系统正常运行时间(秒)
  2. /proc/[PID]/stat
    • #14 utime - 在用户代码中花费的 CPU 时间,以 时钟滴答
    • 为单位
    • #15 stime - 在内核代码中花费的 CPU 时间,以 时钟节拍
    • 为单位
    • #16 cutime - Waited-for children 在用户代码中花费的 CPU 时间(以 时钟节拍)
    • #17 cstime - Waited-for children 在内核代码中花费的 CPU 时间(以 时钟节拍)
    • #22 starttime - 进程开始的时间,以时钟节拍
    • 为单位
  3. 系统的赫兹(每秒时钟滴答数)。

计算

首先我们确定该过程花费的总时间:

total_time = utime + stime

我们还必须决定是否要包括来自子进程的时间。如果我们这样做,那么我们将这些值添加到 total_time:

total_time = total_time + cutime + cstime

接下来,我们将获得自进程开始以来经过的总时间(以 为单位):

seconds = uptime - (starttime / Hertz)

最后我们计算CPU使用百分比:

cpu_usage = 100 * ((total_time / Hertz) / seconds)

另见

Top and ps not showing the same cpu result

How to get total cpu usage in Linux (c++)

Calculating CPU usage of a process in Linux

关于linux - 如何从/proc/pid/stat 获取应用程序的总 CPU 使用率?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16726779/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com