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

如何获得给定进程的实时CPU使用率%?

为了进一步说明这一点:

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

推荐答案

您需要从/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

它以Jiffie为单位告诉您在各种类别中使用的累计CPU时间.你需要把这条线上的值相加,才能得到time_total的测量值.

对于您感兴趣的流程,请同时阅读utimestime,并从/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);

讲得通?

C++相关问答推荐

获取二维数组的最大元素

是否可以在C中进行D3 D12申请?

malloc实现:判断正确的分配对齐

C中的__attributor__((aligned(4),packed))与 struct 的用法

如何解决C中的严格别名?

有没有更简单的方法从用户那里获取数据类型来计算结果

C:scanf(%d&q;,...)输入只有一个减号

如何计算打印二叉搜索树时每行所需的空间?

S在本文中的价值观到底出了什么问题?

如何在VS 2022中正确安装额外的C头文件

Printf()在C中打印终止字符之后的字符,我该如何解决这个问题?

如何在C中定义指向函数的指针并将该指针赋给函数?

C中的数组下标和指针算法给出了不同的结果

在C中打印指针本身

使用复合文字数组初始化的指针数组

在链表中插入一个值

clion.我无法理解 Clion 中发生的 scanf 错误

可以从指针数组中的值初始化指针吗?

如何在 C 中的 Postgres 函数的表中 for 循环

仅使用其内存地址取消引用 C 中的 struct