在Linux中一个进程的计算CPU使用率 [英] Calculating CPU usage of a process in Linux
问题描述
我希望通过编程[用C]在Linux中给定的进程ID计算CPU使用率%。
I want to programatically [in C] calculate CPU usage % for a given process ID in Linux.
我们怎样才能获得实时的CPU使用率%,对于一个给定的过程??
How can we get the realtime CPU usage % for a given process ??
要使它进一步明确 -
To make it further clear -
- 我应该能够确定用于提供进程ID或处理的CPU使用率。
- 这个过程不需要子进程。
- 我想在'C'语言的解决方案。
推荐答案
您需要从的/ proc /&LT解析出数据; PID> / STAT
。这是第几个字段(从文档/文件系统/ proc.txt
在你的内核源代码):
You need to parse out the data from /proc/<PID>/stat
. These are the first few fields (from Documentation/filesystems/proc.txt
in your kernel source):
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
,它看起来像行:
You're probably after utime
and/or stime
. You'll also need to read the cpu
line from /proc/stat
, which looks like:
cpu 192369 7119 480152 122044337 14142 9937 26747 0 0
这告诉你,在各个类别中使用,以jiffies为单位的累计CPU时间。你需要采取在这条线的值的总和来获得 TIME_TOTAL
的措施。
This tells you the cumulative CPU time that's been used in various categories, in units of jiffies. You need to take the sum of the values on this line to get a time_total
measure.
同时读取 UTIME
和 STIME
为你感兴趣的,读的过程中 TIME_TOTAL
从的/ proc / STAT
。然后睡了一秒钟左右,然后再阅读它们。现在可以计算过程的CPU使用率在采样时间,用
Read both utime
and stime
for the process you're interested in, and read time_total
from /proc/stat
. Then sleep for a second or so, and read them all again. You can now calculate the CPU usage of the process over the sampling time, with:
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);
请有意义吗?
这篇关于在Linux中一个进程的计算CPU使用率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!