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

我想知道如何计算一个进程的总 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. 系统的赫兹(每秒时钟滴答数)。
    • 在大多数情况下,getconf CLK_TCK可用于返回时钟滴答数。
    • sysconf(_SC_CLK_TCK) C 函数调用也可用于返回赫兹值。

计算

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

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

https://stackoverflow.com/questions/16726779/

相关文章:

python - 使用 POST 从 Python 脚本发送文件

c - 如何捕获 Control+D 信号?

linux - 是否有将随机垃圾字节写入文件的命令?

linux - 如何给 Linux 用户 sudo 访问权限?

python - 为什么 PyCharm 建议将方法更改为静态?

python - 检测人脸然后自动裁剪图片

python - 排除 os.walk 中的目录

python - 如何在 Anaconda (Conda) 环境中跟踪 pip 安装的软件包?

python - 遍历一个numpy数组

linux - 监听网络端口并将数据保存到文本文件