Linux下CPU获取指定时间的用户态、系统态以及空闲态的时间

实验原理:通过/proc/stat 获取CPU时间,在Linux的内核中,有一个全局变量:Jiffies。 Jiffies代表时间。它的单位随硬件平台的不同而不同。系统里定义了一个常数HZ,代表每秒种最小时间间隔的数目。这样jiffies的单位就是 1/HZ。每个CPU时间片,Jiffies都要加1。通过sleep延迟,两次获取cpu时间,通过各个时间做差值,从而得出CPU处在各个状态的时间。

#!/bin/sh

CPULOG_1=$(cat /proc/stat | grep 'cpu ' | awk '{print $2" "$3" "$4" "$5" "$6" "$7" "$8}')
USR1=$(echo $CPULOG_1 | awk '{print $2}')
NICE1=$(echo $CPULOG_1 | awk '{print $3}')
SYS_IDLE_1=$(echo $CPULOG_1 | awk '{print $4}')
IDLE1=$(echo $CPULOG_1 | awk '{print $5}')
IOWAIT1=$(echo $CPULOG_1 | awk '{print $6}')
IRQ1=$(echo $CPULOG_1 | awk '{print $7}')
SOFTIRQ1=$(echo $CPULOG_1 | awk '{print $8}')
Total_1=$(echo $CPULOG_1 | awk '{print $2+$3+$4+$5+$6+$7+$8}')
Free1=$(echo $CPULOG_1 | awk '{print $3+$5+$6+$7+$8}')
sleep 20
 
CPULOG_2=$(cat /proc/stat | grep 'cpu ' | awk '{print $2" "$3" "$4" "$5" "$6" "$7" "$8}')
USR2=$(echo $CPULOG_2 | awk '{print $2}')
NICE2=$(echo $CPULOG_2 | awk '{print $3}')
SYS_IDLE_2=$(echo $CPULOG_2 | awk '{print $4}')
IDLE2=$(echo $CPULOG_2 | awk '{print $5}')
IOWAIT2=$(echo $CPULOG_2 | awk '{print $6}')
IRQ2=$(echo $CPULOG_2 | awk '{print $7}')
SOFTIRQ2=$(echo $CPULOG_2 | awk '{print $8}')
Total_2=$(echo $CPULOG_2 | awk '{print $2+$3+$4+$5+$6+$7+$8}')
Free2=$(echo $CPULOG_2 | awk '{print $3+$5+$6+$7+$8}')
 
USR=`expr $USR2-$USR1|bc`
NICE=`expr $NICE2-$NICE1|bc`
SYS_IDLE=`expr $SYS_IDLE_2 - $SYS_IDLE_1|bc`
IDLE=`expr $IDLE2-$IDLE1|bc`
IOWAIT=`expr $IOWAIT2-$IOWAIT1|bc`
IRQ=`expr $IRQ2-$IRQ1|bc`
SIRQ=`expr $SOFTIRQ2-$SOFTIRQ1|bc`
Total=`expr $Total_2 - $Total_1|bc`
Free=`expr $Free2-$Free1|bc`
echo $USR user
echo $NICE nice_
echo $SYS_IDLE sys
echo $IDLE idle
echo $IOWAIT iowait
echo $IRQ irq
echo $SIRQ sirq 
echo $Total all
echo $Free free_



你可能感兴趣的:(Linux下CPU获取指定时间的用户态、系统态以及空闲态的时间)