cod*_*eak 93 c linux cpu-usage
我想以编程方式[在C中]计算Linux中给定进程ID的CPU使用率%.
我们如何获得给定进程的实时CPU使用率%?
进一步明确:
caf*_*caf 144
您需要解析数据/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
Run Code Online (Sandbox Code Playgroud)
你可能在utime和/或之后stime.您还需要阅读以下cpu行/proc/stat:
cpu 192369 7119 480152 122044337 14142 9937 26747 0 0
Run Code Online (Sandbox Code Playgroud)
这将告诉您在各种类别中使用的累计CPU时间,以jiffies为单位.您需要获取此行上的值的总和以获得time_total度量.
同时读取utime并stime进行过程中,你有兴趣,并阅读time_total来自/proc/stat.然后睡一会儿左右,再读一遍.您现在可以在采样时间内计算进程的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);
Run Code Online (Sandbox Code Playgroud)
合理?
vpr*_*m86 11
getrusage()可以帮助您确定当前进程或其子进程的使用情况
更新: 我记不起API了.但所有细节都在/ proc/PID/stat中,所以如果我们可以解析它,我们就可以获得百分比.
编辑: 由于CPU%不是直接计算,你可以在这里使用抽样的东西.在某个时间点读取ctime和utime以获取PID,并在1秒后再次读取相同的值.找出差异并除以百.您将在过去一秒钟内获得该流程的使用权.
(如果有很多处理器,可能会变得更复杂)
小智 6
像我这样的小块很容易迈出一步:)
读取/ proc/stat的第一行以获取total_cpu_usage1
sscanf(line,"%*s %llu %llu %llu %llu",&user,&nice,&system,&idle);
total_cpu_usage1 = user + nice + system + idle;
Run Code Online (Sandbox Code Playgroud)
read/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
....)
Run Code Online (Sandbox Code Playgroud)
现在总结usertime和系统时间并得到proc_times1
现在等待1秒或更长时间
再做一次,得到total_cpu_usage2和proc_times2
公式是:
(number of processors) * (proc_times2 - proc_times1) * 100 / (float) (total_cpu_usage2 - total_cpu_usage1)
Run Code Online (Sandbox Code Playgroud)
你可以从/ proc/cpuinfo获得cpu的数量
我写了两个基于cafs的小C函数回答来计算一个进程的用户+内核cpu使用情况:https: //github.com/fho/code_snippets/blob/master/c/getusage.c