我想用C语言以编程方式计算Linux中给定进程ID的CPU使用率。
如何获取给定进程的实时CPU使用率?
为了进一步明确这一点:
发布于 2009-09-15 00:31:07
您需要从/proc/<PID>/stat
中解析出数据。以下是前几个字段(来自内核源代码中的Documentation/filesystems/proc.txt
):
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
。您还需要读取/proc/stat
中的cpu
行,如下所示:
cpu 192369 7119 480152 122044337 14142 9937 26747 0 0
它以jiffies为单位告诉您在各种类别中使用的累积CPU时间。您需要将此行上的值求和,以获得time_total
度量。
阅读您感兴趣的进程的utime
和stime
,并阅读/proc/stat
中的time_total
。然后睡上一小会,然后再读一遍。现在,您可以使用以下命令计算采样时间内进程的CPU使用率:
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);
讲得通?
发布于 2009-09-14 09:01:30
getrusage()可以帮助您确定当前进程或其子进程的使用情况
更新: API我不记得有了。但是所有的细节都在/proc/PID/stat,中,所以如果我们可以解析它,我们就可以得到百分比。
编辑:由于CPU%不是直接计算的,你可以在这里使用采样类的东西。在某个时间点读取PID的ctime和utime,并在1秒后再次读取相同的值。找出差值并除以100。在过去的一秒钟内,您将获得该进程的利用率。
(如果有许多处理器,可能会变得更复杂)
发布于 2012-09-26 22:29:56
对于像我这样的初学者来说,一步一步来:
获取total_cpu_usage1
.的
/proc/stat
的第一行 sscanf(line,"%*s %llu %llu %llu %llu",&user,&nice,&system,&idle);
total_cpu_usage1 = user + nice + system + idle;
/proc/pid/stat
,其中pid
是您想要了解CPU使用情况的进程的PID,如下所示: sscanf(line,
"%*d %*s %*c %*d" //pid,command,state,ppid
"%*d %*d %*d %*d %*u %*lu %*lu %*lu %*lu"
"%lu %lu" //usertime,systemtime
"%*ld %*ld %*ld %*ld %*ld %*ld %*llu"
"%*lu", //virtual memory size in bytes
....)
usertime
和systemtime
相加,并让proc_times1
usertime
等待1秒或更长时间total_cpu_usage2
和systemtime
公式是:
(number of processors) * (proc_times2 - proc_times1) * 100 / (float) (total_cpu_usage2 - total_cpu_usage1)
您可以从/proc/cpuinfo
获取CPU的数量。
https://stackoverflow.com/questions/1420426
复制相似问题