c - 在其挂钟运行时间的一部分上测量守护进程 CPU 利用率

标签 c linux time profiling daemon

我正在处理一个与网络相关的守护进程:它接收数据,处理数据,然后将数据吐出。我想通过分析它并降低它的 CPU 使用率来提高这个守护进程的性能。我可以在 Linux 上使用 gprof 轻松完成此操作。但是,我也想使用“时间”之类的东西来衡量它在一段时间内的总 CPU 使用率。如果可能的话,我想在一个小于它的总运行时间的时间段内计时:因此,我想启动守护进程,稍等片刻,生成 CPU 统计信息,停止生成它们,然后在稍后的某个时间停止守护进程.

“时间”命令对我来说效果很好,但它似乎要求我将守护进程作为时间的 child 来启动和停止。有没有一种方法可以仅测量守护程序挂钟时间的一部分的 CPU 利用率?

最佳答案

/proc/<pid>/stat文件包含必要的信息 - 你在寻找 utimestime领域。这些是进程使用的用户模式和内核模式 CPU 时间的累积计数器;在测量间隔开始时读取它们,然后在结束时再次读取它们并计算差异。

这将为您提供以 jiffies 为单位的已用 CPU 时间。要确定以 jiffies 为单位的挂钟总耗用时间(以便您可以转换为平均利用率),请对 cpu0 上的数字求和在线 /proc/stat (之前和之后,就像 /proc/<pid>/stat )。

这是/proc/<pid>/stat中前几个字段的布局, 来自 Documentation/filesystems/proc.txt在 Linux 源代码中:

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

关于c - 在其挂钟运行时间的一部分上测量守护进程 CPU 利用率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2918274/

相关文章:

java - Android 游戏时间处理

r - 识别时间数据的差距

c - 使用 OpenMP 并行化嵌套循环

C 统一码 : How do I apply C11 standard amendment DR488 fix to C11 standard function c16rtomb()?

c - 如何向内部函数添加断点

用于 RISCV 多核处理器的 Linux 移植

linux - GStreamer 上的 'blacklisted' 是什么意思?

c - 取消引用指针的后增量?

linux - 在 bash 中设置带有前导数字的环境变量

javascript - 在 setTimeout 调用期间超过最大调用堆栈大小