本文共 2447 字,大约阅读时间需要 8 分钟。
mpstat,top等命令都能显示出当前cpu的平均负载。这里总结一下实现原理。和磁盘容量相同,主要信息依然来自proc文件夹中的文件。
文件中包含了所有cpu活动信息,所有值都是从系统启动开始累计到当前的值。
cat /proc/stat 可以看到:
01 | cpu 338689 491 148834 421508071 144932 147 2393 0 0 |
02 | cpu0 76231 102 27936 105287866 65496 131 1279 0 0 |
03 | cpu1 61032 124 33826 105461911 7878 5 327 0 0 |
04 | cpu2 99959 119 48815 105348407 61499 4 270 0 0 |
05 | cpu3 101465 145 38256 105409886 10058 5 516 0 0 |
06 | intr #内容过长,省略。。 |
07 | btime 1404887530 |
08 | processes 67847 |
09 | procs_running 1 |
10 | procs_blocked 0 |
11 | softirq 143606318 0 48818619 0 7394692 207606 0 2 37354272 37556 49793571 |
12 | per_cpu_ctxt 89704992 16150309 18333905 18496328 |
“cpu”开头的几行给出的是cpu不同状态下时间片(单位:jiffies)。
cpu为总的信息,cpu0,cpu1….cpu<n>对应各个cpu的信息。
“cpu”后面的数值是对应(user、nice、system、idle、iowait、irq、softirq、stealstolen、guest)的9元组:
数值对应cpu这行。
urt 用户时间(User time) 从系统启动开始累计到当前时刻,处于用户态的运行时间,不包括nice啥时间。
net Nice时间(Nice time) 系统调整进程优先级所花费的时间
smt 系统时间(System time) 从系统启动开始累计到当前时刻,处于核心态的运行时间
iet 空闲时间(Idle time) 系统空闲时间
wgt 等待时间(Waiting time) 从系统启动开始累计到当前时刻,IO等待时间(since 2.5.41)
hdt 硬中断处理时间(Hard Irq time) 从系统启动开始累计到当前时刻,硬中断时间(since 2.6.0-test4)
sqt 丢失时间(Steal time) 从系统启动开始累计到当前时刻,软中断时间(since 2.6.0-test4)
以下两个参数可能有的系统不存在。
slt 丢失时间(Steal time) 丢失的时间片,如果系统运行于虚拟机中,则会有时间片用在别的操作系统上。 which is the time spent in other operating systems when running in a virtualized environment(since 2.6.11)
gst 客户时间(guest time) 系统中运行了虚拟机,会有时间片用于调度虚拟机中的操作系统内核。 which is the time spent running a virtual CPU for guest operating systems under the control of the Linux kernel(since 2.6.24)
“intr”这行给出中断的信息,第一个为自系统启动以来,发生的所有的中断的次数;然后每个数对应一个特定的中断自系统启动以来所发生的次数。
“ctxt”给出了自系统启动以来CPU发生的上下文交换的次数。“btime”给出了从系统启动到现在为止的时间,单位为秒。(实际查看发现这个值不变,原因未知)“processes” (total_forks) 自系统启动以来所创建的任务的个数目。“procs_running”当前运行队列的任务的数目。“procs_blocked”当前被阻塞的任务的数目。
注意这里使用的是一个阶段的差值来计算使用率的,这个使用率是个平均值。
注意最后两个数值(slt,gst)可能有的版本不存在。
01 | cut = urt + net + smt + iet + wgt + hdt + sqt + slt + gst |
02 | rate[ 'us' ] = (urt + net) / cut * 100 #us — (User time)用户空间占用CPU的百分比。 |
03 | rate[ 'sy' ] = (smt + hdt + sqt) / cut * 100 #sy — (System time)内核空间占用CPU的百分比。 |
04 | rate[ 'ni' ] = net / cut * 100 #ni — (Nice time)改变过优先级的进程占用CPU的百分比 |
05 | rate[ 'id' ] = iet / cut * 100 #id — (Idle time)空闲CPU百分比 |
06 | rate[ 'wa' ] = wgt / cut * 100 #wa — (Waiting time)IO等待占用CPU的百分比 |
07 | rate[ 'hi' ] = hdt / cut * 100 #hi — (Hardware IRQ time)硬中断占用CPU的百分比 |
08 | rate[ 'si' ] = sqt / cut * 100 #si — (Software Interrupts)软中断占用CPU的百分比 |
09 | rate[ 'st' ] = slt / cut * 100 #st — (Steal time)丢失事件占用CPU的百分比 |
10 | rate[ 'gt' ] = gst / cut * 100 #gt — (Guest time)系统中虚拟机使用的CPU占总CPU的百分比 |
转载请注明: »