我想知道如何计算一个进程的总 CPU 使用率。
如果我这样做 cat /proc/<em>pid</em>/stat
,我认为相关领域是(taken from lindevdoc.org):
那么总时间是花费在字段 14 到 17 的总和上吗?
最佳答案
要计算特定进程的 CPU 使用率,您需要以下内容:
/proc/uptime
#1
系统正常运行时间(秒)/proc/[PID]/stat
#14
utime
- 在用户代码中花费的 CPU 时间,以 时钟滴答#15
stime
- 在内核代码中花费的 CPU 时间,以 时钟节拍#16
cutime
- Waited-for children 在用户代码中花费的 CPU 时间(以 时钟节拍) #17
cstime
- Waited-for children 在内核代码中花费的 CPU 时间(以 时钟节拍) #22
starttime
- 进程开始的时间,以时钟节拍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/