如何从C中通过PID在Linux中计算进程的CPU使用率? [英] How to calculate the CPU usage of a process by PID in Linux from C?

查看:31
本文介绍了如何从C中通过PID在Linux中计算进程的CPU使用率?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以编程方式[用 C] 计算 Linux 中给定进程 ID 的 CPU 使用率.

I want to programmatically [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?

进一步说明:

  • 我应该能够确定提供的进程 ID 或进程的 CPU 使用率.
  • 进程不必是子进程.
  • 我想要C"语言的解决方案.

推荐答案

你需要从/proc//stat中解析出数据.这些是前几个字段(来自内核源代码中的 Documentation/filesystems/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.您还需要读取 /proc/stat 中的 cpu 行,如下所示:

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

这会告诉您在各种类别中使用的累积 CPU 时间,以 jiffies 为单位.您需要对这一行上的值求和以获得 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.

读取utimestime 以获取您感兴趣的进程,并从/proc/stat<读取time_total/代码>.然后睡一会左右,再读一遍.您现在可以计算采样时间内进程的 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);

有意义吗?

这篇关于如何从C中通过PID在Linux中计算进程的CPU使用率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆