如何在C语言中通过PID在Linux中计算进程的CPU使用率?

时间:2009-09-14 08:58:12

标签: c linux cpu-usage

我希望以编程方式[在C中]计算Linux中给定进程ID的CPU使用率。

我们如何获得给定流程的实时CPU使用率?

进一步明确:

  • 我应该能够确定所提供的processid或进程的CPU使用率。
  • 这个过程不一定是子进程。
  • 我想用'C'语言解决方案。

12 个答案:

答案 0 :(得分:140)

您需要解析/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之后。您还需要阅读cpu中的/proc/stat行,其内容如下:

cpu  192369 7119 480152 122044337 14142 9937 26747 0 0

这将告诉您在各种类别中使用的累计CPU时间,以jiff为单位。您需要获取此行上的值之和才能获得time_total度量。

阅读您感兴趣的流程utimestime,并阅读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);

有意义吗?

答案 1 :(得分:11)

getrusage()可以帮助您确定当前流程或其子级的使用情况

<强>更新 我记不起API了。但所有细节都在/ proc / PID / stat中,所以如果我们可以解析它,我们就可以得到百分比。

修改 由于CPU%不是直接计算的,你可以在这里使用抽样的东西。在某个时间点读取ctime和utime以获取PID,并在1秒后再次读取相同的值。找出差异并除以百。您将在过去一秒钟内获得该流程的使用权。

(如果有很多处理器,可能会变得更复杂)

答案 2 :(得分:6)

像我这样的小块很容易迈出一步:)

读取/ proc / stat的第一行以获取total_cpu_usage1

sscanf(line,"%*s %llu %llu %llu %llu",&user,&nice,&system,&idle);
total_cpu_usage1 = user + nice + system + idle;

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
....)

现在总结usertime和系统时间并得到proc_times1

现在等待1秒或更长时间

再次执行,并获取total_cpu_usage2和proc_times2

公式为:

(number of processors) * (proc_times2 - proc_times1) * 100 / (float) (total_cpu_usage2 - total_cpu_usage1)

你可以从/ proc / cpuinfo

获得cpus的数量

答案 3 :(得分:5)

我写了两个基于cafs的小C函数回答来计算一个进程的用户+内核cpu使用情况: https://github.com/fho/code_snippets/blob/master/c/getusage.c

答案 4 :(得分:3)

您可以阅读manpage for proc以获取更多详细信息,但总的来说,您可以阅读/ proc / [number] / stat来获取有关流程的信息。 “ps”命令也使用它。

所有字段及其scanf格式说明符都记录在proc manpag e。

以下是manpage复制的一些信息(很长):

          pid %d The process ID.

          comm %s
                 The  filename of the executable, in parentheses.  This is
                 visible whether or not the executable is swapped out.

          state %c
                 One character from the string "RSDZTW" where  R  is  runâ
                 ning,  S is sleeping in an interruptible wait, D is waitâ
                 ing in uninterruptible disk sleep,  Z  is  zombie,  T  is
                 traced or stopped (on a signal), and W is paging.

          ppid %d
                 The PID of the parent.

          pgrp %d
                 The process group ID of the process.

          session %d
                 The session ID of the process.

          tty_nr %d
                 The tty the process uses.

          tpgid %d
                 The  process group ID of the process which currently owns
                 the tty that the process is connected to.

答案 5 :(得分:2)

看看“pidstat”命令,听起来就像你需要的那样。

答案 6 :(得分:2)

这是我的解决方案......

/*
this program is looking for CPU,Memory,Procs also u can look glibtop header there was a lot of usefull function have fun..
systeminfo.c
*/
#include <stdio.h>
#include <glibtop.h>
#include <glibtop/cpu.h>
#include <glibtop/mem.h>
#include <glibtop/proclist.h>



int main(){

glibtop_init();

glibtop_cpu cpu;
glibtop_mem memory;
glibtop_proclist proclist;

glibtop_get_cpu (&cpu);
glibtop_get_mem(&memory);


printf("CPU TYPE INFORMATIONS \n\n"
"Cpu Total : %ld \n"
"Cpu User : %ld \n"
"Cpu Nice : %ld \n"
"Cpu Sys : %ld \n"
"Cpu Idle : %ld \n"
"Cpu Frequences : %ld \n",
(unsigned long)cpu.total,
(unsigned long)cpu.user,
(unsigned long)cpu.nice,
(unsigned long)cpu.sys,
(unsigned long)cpu.idle,
(unsigned long)cpu.frequency);

printf("\nMEMORY USING\n\n"
"Memory Total : %ld MB\n"
"Memory Used : %ld MB\n"
"Memory Free : %ld MB\n"
"Memory Buffered : %ld MB\n"
"Memory Cached : %ld MB\n"
"Memory user : %ld MB\n"
"Memory Locked : %ld MB\n",
(unsigned long)memory.total/(1024*1024),
(unsigned long)memory.used/(1024*1024),
(unsigned long)memory.free/(1024*1024),
(unsigned long)memory.shared/(1024*1024),
(unsigned long)memory.buffer/(1024*1024),
(unsigned long)memory.cached/(1024*1024),
(unsigned long)memory.user/(1024*1024),
(unsigned long)memory.locked/(1024*1024));

int which,arg;
glibtop_get_proclist(&proclist,which,arg);
printf("%ld\n%ld\n%ld\n",
(unsigned long)proclist.number,
(unsigned long)proclist.total,
(unsigned long)proclist.size);
return 0;
}

makefile is
CC=gcc
CFLAGS=-Wall -g
CLIBS=-lgtop-2.0 -lgtop_sysdeps-2.0 -lgtop_common-2.0

cpuinfo:cpu.c
$(CC) $(CFLAGS) systeminfo.c -o systeminfo $(CLIBS)
clean:
rm -f systeminfo

答案 7 :(得分:1)

当您想要监视器指定的进程时,通常是通过脚本完成的。这是perl的例子。这使得百分比与top相同,将其分解为一个CPU。然后当某个进程处于活动状态并使用2个线程时,cpu使用率可能超过100%。特别关注如何计算cpu核心:D 然后让我展示我的榜样:

#!/usr/bin/perl

my $pid=1234; #insert here monitored process PID

#returns current process time counters or single undef if unavailable
#returns:  1. process counter  , 2. system counter , 3. total system cpu cores
sub GetCurrentLoads {
    my $pid=shift;
    my $fh;
    my $line;
    open $fh,'<',"/proc/$pid/stat" or return undef;
    $line=<$fh>;
    close $fh;
    return undef unless $line=~/^\d+ \([^)]+\) \S \d+ \d+ \d+ \d+ -?\d+ \d+ \d+ \d+ \d+ \d+ (\d+) (\d+)/;
    my $TimeApp=$1+$2;
    my $TimeSystem=0;
    my $CpuCount=0;
    open $fh,'<',"/proc/stat" or return undef;
    while (defined($line=<$fh>)) {
        if ($line=~/^cpu\s/) {
            foreach my $nr ($line=~/\d+/g) { $TimeSystem+=$nr; };
            next;
        };
        $CpuCount++ if $line=~/^cpu\d/;
    }
    close $fh;
    return undef if $TimeSystem==0;
    return $TimeApp,$TimeSystem,$CpuCount;
}

my ($currApp,$currSys,$lastApp,$lastSys,$cores);
while () {
    ($currApp,$currSys,$cores)=GetCurrentLoads($pid);
    printf "Load is: %5.1f\%\n",($currApp-$lastApp)/($currSys-$lastSys)*$cores*100 if defined $currApp and defined $lastApp and defined $currSys and defined $lastSys;
    ($lastApp,$lastSys)=($currApp,$currSys);
    sleep 1;
}

我希望它可以帮助您进行任何监控。当然你应该使用scanf或其他C函数来转换我用过的任何perl regexpes到C源代码。 当然,1秒睡觉不是强制性的。你可以随时使用。效果是,您将在指定的时间段内获得负担。当你将它用于监控时,当然应该把它放在外面。这是必需的,因为监视通常会定期调用脚本,脚本应该尽快完成他的工作。

答案 8 :(得分:0)

安装psacctacct包。然后使用sa命令显示用于各种命令的CPU时间。 sa man page

来自nixCraft网站的一个不错的howto

答案 9 :(得分:0)

我认为值得一看GNU“time”命令源代码。 time 它输出用户/系统CPU时间以及实际经过的时间。它调用wait3 / wait4系统调用(如果可用),否则调用系统调用次数。 wait *系统调用返回“rusage”结构变量,并且系统调用返回“tms”。此外,您还可以查看getrusage系统调用,它也会返回非常有趣的计时信息。 time

答案 10 :(得分:0)

不是从proc解析这个,而是可以使用getrusage()或clock_gettime()等函数,并将cpu使用率计算为cpu上使用的进程/线程的比率或挂钟时间和时间。

答案 11 :(得分:0)

使用strace发现需要按时间段计算CPU使用率:

# top -b -n 1 -p 3889
top - 16:46:37 up  1:04,  3 users,  load average: 0.00, 0.01, 0.02
Tasks:   1 total,   0 running,   1 sleeping,   0 stopped,   0 zombie
%Cpu(s):  0.0 us,  0.0 sy,  0.0 ni,100.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
KiB Mem :  5594496 total,  5158284 free,   232132 used,   204080 buff/cache
KiB Swap:  3309564 total,  3309564 free,        0 used.  5113756 avail Mem 

  PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND
 3889 root      20   0  162016   2220   1544 S   0.0  0.0   0:05.77 top
# strace top -b -n 1 -p 3889
.
.
.
stat("/proc/3889", {st_mode=S_IFDIR|0555, st_size=0, ...}) = 0
open("/proc/3889/stat", O_RDONLY)       = 7
read(7, "3889 (top) S 3854 3889 3854 3481"..., 1024) = 342
.
.
.

nanosleep({0, 150000000}, NULL)         = 0
.
.
.
stat("/proc/3889", {st_mode=S_IFDIR|0555, st_size=0, ...}) = 0
open("/proc/3889/stat", O_RDONLY)       = 7
read(7, "3889 (top) S 3854 3889 3854 3481"..., 1024) = 342
.
.
.