/proc/stat
访问量:2245

一、简介

/proc/stat 文件z中,包含了系统启动以来的很多系统相关的统计信息,比如cpu、中断情况、启动时间、上下文切换次数、运行中的进程等。其文件内容一般如下:

cpu  2002 28 4829 702857 5869 70 30 0 0 0
cpu0 2002 28 4829 702857 5869 70 30 0 0 0
intr 370358 192 126 0 3 3299 0 0 0 1 0 0 0 1270 0 0 24748 747 26969 67 4876 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 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 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 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 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 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 
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 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 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
ctxt 654618
btime 1559614293 
processes 4042
procs_running 1
procs_blocked 0
softirq 301870 0 123098 3384 4499 30439 0 1998 0 568 137884

描述:

cpu后面展示的是时间,其单位是jiffies,其中jiffies是内核中的一个全局变量,用来记录自系统启动一来产生的节拍数,在linux中,一个节拍大致可理解为操作系统进程调度的最小时间片,不同linux内核可能值有不同,通常在1ms到10ms之间。

cpucpu0的区别:一个系统里面可能会存在多个cpu,然后就会使用cpu0、cpu1、cpu2...来表示,其中cpu0,代表一个cpu的相关统计,cpu代表所有的cpu的统计。

ctxt 系统上下文切换次数。

btime 系统启动的时间,单位秒,如上面,1559614293 转为时间字符串为2019-06-4 10:11:33

processes 系统启动后所创建过的进程数量。

procs_running:处于Runnable状态的进程个数。

procs_blocked:处于等待I/O完成的进程个数,即被阻塞的进程数。

softirq:软中断的时间。

1、关于cpu的详细描述

nameusernicesystemidleiowaitirrqsoftirqstealguestguest_nice
cpu200228482970285758697030000
cpu0200228482970285758697030000

字段描述:

cpu指标含义时间单位备注
user用户态时间jiffies一般/高优先级,仅统计nice<=0
nicenice用户态时间jiffies低优先级,仅统计nice>0
system内核态时间jiffies
idle空闲时间jiffies不包含IO等待时间
iowaitI/O等待时间jiffies硬盘IO等待时间
irq硬中断时间jiffies
softirq软中断时间jiffies
steal被盗时间jiffies虚拟化环境中运行其他操作系统上花费的时间(since Linux 2.6.11)
guest来宾时间jiffies操作系统运行虚拟CPU花费的时间(since Linux 2.6.24)
guest_nicenice来宾时间jiffies运行一个带nice值的guest花费的时间(since Linux 2.6.33)

二、应用

1、如何计算cpu空闲百分比

采样两个足够短的时间间隔的cpu快照,标记为t1、t2。计算t1时间的cpu的空闲时间idle1(cpu空闲时间)和cpu的总时间total1,计算t2时间的cpu的空闲时间idle2(cpu空闲时间)和cpu的总时间total2。

备注:cpu的总时间为:user + nice + system + idle + iowait + irq + softirq + stealstolen + guest时间总和。

于是cpu的空闲率为

100 *  (idle2 - idle1) / (total2 - total1)

有了cpu的空闲百分比,那么cpu的使用率,就比较好计算了,如下:

100  - 100 *  (idle2 - idle1) / (total2 - total1)

利用,这个方法,我们可以很容易求出用户态时间百分比、内核态时间百分比、cpu Io等待百分比等。