我正在处理一个与网络相关的守护进程:它接收数据,处理数据,然后将数据吐出。我想通过分析它并降低它的 CPU 使用率来提高这个守护进程的性能。我可以在 Linux 上使用 gprof 轻松完成此操作。但是,我也想使用“时间”之类的东西来衡量它在一段时间内的总 CPU 使用率。如果可能的话,我想在一个小于它的总运行时间的时间段内计时:因此,我想启动守护进程,稍等片刻,生成 CPU 统计信息,停止生成它们,然后在稍后的某个时间停止守护进程.
“时间”命令对我来说效果很好,但它似乎要求我将守护进程作为时间的 child 来启动和停止。有没有一种方法可以仅测量守护程序挂钟时间的一部分的 CPU 利用率?
最佳答案
/proc/<pid>/stat
文件包含必要的信息 - 你在寻找 utime
和 stime
领域。这些是进程使用的用户模式和内核模式 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/