技术分享

linux中top性能分析工具指标

2019-12-20  本文已影响0人  tracy_668

time

top命令的TIME/TIME+是指的进程所使用的CPU时间,不是进程启动到现在的时间,因此,如果一个进程使用的cpu很少,那即使这个进程已经存在N长时间,TIME/TIME+也是很小的数值

此外,如果你的系统有多个CPU,或者是多核CPU的话,那么,进程占用多个cpu的时间是累加的。

image.png

例如:257:14.655代表的时间是:

从右到左分别是百分之一秒,十分之一秒,秒,十秒,分钟

这个就是257分钟,10秒,4秒,十分之6秒,百分之5秒、千分之5秒,是按位来计算的。

cpu

总结来说某个进程的CPU使用率就是这个进程在一段时间内占用的CPU时间占总的CPU时间的百分比。

比如某个开启多线程的进程1s内占用了CPU0 0.6s, CPU1 0.9s, 那么它的占用率是150%。这样就不难理解上例中cputest进程CPU占用率为800%这个结果了。

实现CPU使用率统计程序
某进程cpu使用率 = 该进程cpu时间 / 总cpu时间。

/proc/pid/stat中可以得出进程自启动以来占用的cpu时间。以bash进程为例:

79 (bash) S 46 79 79 34816 0 0 0 0 0 0 46 135 387954 4807 20 0 1 0 6114 232049254400 873 18446744073709551615 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

第14项utime和第15项stime分别表示bash自启动起来,执行用户代码态占用的时间和执行内核态代码占用的时间,单位是clock tick,clock tick是时间单位。这两项的详细解释如下(摘自man proc):

              (14) utime  %lu
                        Amount  of  time  that  this process has been scheduled in user mode, measured in clock ticks (divide by sysconf(_SC_CLK_TCK)).  This includes
                        guest time, guest_time (time spent running a virtual CPU, see below), so that applications that are not aware of the guest time field  do  not
                        lose that time from their calculations.

              (15) stime  %lu
                        Amount of time that this process has been scheduled in kernel mode, measured in clock ticks (divide by sysconf(_SC_CLK_TCK)).

每个clock tick占用多少时间呢?
可以通过sysconf(_SC_CLK_TCK)获取1秒内有多少个clock tick(通常是100)。也就是说1 clock tick为1 / 100秒。

有了上面的基础,
我们可以每隔period秒读取/proc/pid/stat,解析其中的utime和stime,将其和(utime+stime)减去上一次采样时这两项的和(lastutime + laststime),这就是period秒内该进程占用CPU的时间,单位为clock tick。

总的CPU时间为period * sysconf(_SC_CLK_TCK),单位也为clock tick。

某进程cpu使用率 = ((utime+stime) - (lastutime + laststime)) / (period * sysconf(_SC_CLK_TCK))

很简单,每隔两秒采一次样,计算这两秒内指定进程的CPU使用率。

上一篇 下一篇

猜你喜欢

热点阅读