Skip to content

Commit 82818b0

Browse files
author
Wangpan
committed
add cpu rate collecting script
1 parent 76ddfed commit 82818b0

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

cpu_rate.sh

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
#!/bin/bash
2+
interval=3
3+
cpu_num=`cat /proc/stat | grep cpu[0-9] -c`
4+
5+
start_idle=()
6+
start_total=()
7+
cpu_rate=()
8+
9+
cpu_rate_file=./`hostname`_cpu_rate.csv
10+
if [ -f ${cpu_rate_file} ]; then
11+
mv ${cpu_rate_file} ${cpu_rate_file}.`date +%m_%d-%H_%M_%S`.bak
12+
fi
13+
for((i=0;i<${cpu_num};i++))
14+
{
15+
echo -n "cpu$i," >> ${cpu_rate_file}
16+
}
17+
echo -n "cpu_avg" >> ${cpu_rate_file}
18+
echo "" >> ${cpu_rate_file}
19+
20+
while(true)
21+
do
22+
for((i=0;i<${cpu_num};i++))
23+
{
24+
start=$(cat /proc/stat | grep "cpu$i" | awk '{print $2" "$3" "$4" "$5" "$6" "$7" "$8}')
25+
start_idle[$i]=$(echo ${start} | awk '{print $4}')
26+
start_total[$i]=$(echo ${start} | awk '{printf "%.f",$1+$2+$3+$4+$5+$6+$7}')
27+
}
28+
start=$(cat /proc/stat | grep "cpu " | awk '{print $2" "$3" "$4" "$5" "$6" "$7" "$8}')
29+
start_idle[${cpu_num}]=$(echo ${start} | awk '{print $4}')
30+
start_total[${cpu_num}]=$(echo ${start} | awk '{printf "%.f",$1+$2+$3+$4+$5+$6+$7}')
31+
sleep ${interval}
32+
for((i=0;i<${cpu_num};i++))
33+
{
34+
end=$(cat /proc/stat | grep "cpu$i" | awk '{print $2" "$3" "$4" "$5" "$6" "$7" "$8}')
35+
end_idle=$(echo ${end} | awk '{print $4}')
36+
end_total=$(echo ${end} | awk '{printf "%.f",$1+$2+$3+$4+$5+$6+$7}')
37+
idle=`expr ${end_idle} - ${start_idle[$i]}`
38+
total=`expr ${end_total} - ${start_total[$i]}`
39+
idle_normal=`expr ${idle} \* 100`
40+
cpu_usage=`expr ${idle_normal} / ${total}`
41+
cpu_rate[$i]=`expr 100 - ${cpu_usage}`
42+
echo "The CPU$i Rate : ${cpu_rate[$i]}%"
43+
echo -n "${cpu_rate[$i]}," >> ${cpu_rate_file}
44+
}
45+
end=$(cat /proc/stat | grep "cpu " | awk '{print $2" "$3" "$4" "$5" "$6" "$7" "$8}')
46+
end_idle=$(echo ${end} | awk '{print $4}')
47+
end_total=$(echo ${end} | awk '{printf "%.f",$1+$2+$3+$4+$5+$6+$7}')
48+
idle=`expr ${end_idle} - ${start_idle[$i]}`
49+
total=`expr ${end_total} - ${start_total[$i]}`
50+
idle_normal=`expr ${idle} \* 100`
51+
cpu_usage=`expr ${idle_normal} / ${total}`
52+
cpu_rate[${cpu_num}]=`expr 100 - ${cpu_usage}`
53+
echo "The Average CPU Rate : ${cpu_rate[${cpu_num}]}%"
54+
echo -n "${cpu_rate[${cpu_num}]}" >> ${cpu_rate_file}
55+
echo "------------------"
56+
echo "" >> ${cpu_rate_file}
57+
done

0 commit comments

Comments
 (0)