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

时间:2010-05-27 03:26:19

标签: c linux time profiling daemon

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

“time”命令对我来说效果很好,但似乎要求我作为时间的孩子启动和停止守护进程。有没有办法只测量守护进程的挂钟时间的一部分CPU利用率?

1 个答案:

答案 0 :(得分:2)

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

这会让你在jiffies中使用CPU时间。要确定jiffies中经过的总挂钟时间(因此您可以转换为平均利用率),请对cpu0/proc/stat行上的数字求和(之前和之后,就像/proc/<pid>/stat

这是/proc/<pid>/stat中前几个字段的布局,来自Linux源代码中的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