2013-05-15 79 views
1

即時嘗試編寫一個bash腳本來讀取每個進程的CPU使用情況。 但是,我認爲我做錯了。當我測試這個腳本時,它給了我一個不正確的百分比。 繼承人的代碼:每個進程使用bash腳本的CPU使用率

prev_total=0 
prev_idle=0 
prev_processtotal=0 
prev_utime=0 
while true; do 
cpu=`cat /proc/stat | head -n1 | sed 's/cpu //'` 
user=`echo $cpu | awk '{print $1}'` 
system=`echo $cpu | awk '{print $2}'` 
nice=`echo $cpu | awk '{print $3}'` 
idle=`echo $cpu | awk '{print $4}'` 
wait=`echo $cpu | awk '{print $5}'` 
irq=`echo $cpu | awk '{print $6}'` 
srq=`echo $cpu | awk '{print $7}'` 
zero=`echo $cpu | awk '{print $8}'` 
total=$(($user+$system+$nice+$idle+$wait+$irq+$srq+$zero)) 
diff_idle=$(($idle-$prev_idle)) 
diff_total=$(($total-$prev_total)) 
usage=$(($((1000*$(($diff_total-$diff_idle))/$diff_total+5))/10)) 
process=`cat /proc/20966/stat` 
utime=`echo $process | awk '{print $14}'` 
stime=`echo $process | awk '{print $15}'` 
cutime=`echo $process | awk '{print $16}'` 
cstime=`echo $process | awk '{print $17}'` 
processtotal=$(($utime+$stime+$cutime+$cstime)) 
diff_processtotal=$(($processtotal-$prev_processtotal)) 
diff_utime=$(($utime-$prev_utime)) 
processusage=$(($((1000*$(($diff_processtotal-$diff_utime))/$diff_processtotal+5))/10)) 
clear 
echo "total cpu usage: $usage%" 
echo "one selected process: $processusage%" 
prev_total=$total 
prev_idle=$idle 
prev_processtotal=$processtotal 
prev_utime=$utime 
sleep 1 
done 

IM有點丟在這裏,所以任何幫助將是非常讚賞:)

回答

0
prev_total=0 
prev_idle=0 
prev_processtotal=0 
prev_utime=0 
while true; do 
cpu=`cat /proc/stat | head -n1 | sed 's/cpu //'` 
user=`echo $cpu | awk '{print $1}'` 
system=`echo $cpu | awk '{print $2}'` 
nice=`echo $cpu | awk '{print $3}'` 
idle=`echo $cpu | awk '{print $4}'` 
wait=`echo $cpu | awk '{print $5}'` 
irq=`echo $cpu | awk '{print $6}'` 
srq=`echo $cpu | awk '{print $7}'` 
zero=`echo $cpu | awk '{print $8}'` 
total=$(($user+$system+$nice+$idle+$wait+$irq+$srq+$zero)) 
diff_idle=$(($idle-$prev_idle)) 
diff_total=$(($total-$prev_total)) 
usage=$(($((1000*$(($diff_total-$diff_idle))/$diff_total+5))/10)) 
process=`cat /proc/19240/stat` 
utime=`echo $process | awk '{print $14}'` 
stime=`echo $process | awk '{print $15}'` 
cutime=`echo $process | awk '{print $16}'` 
cstime=`echo $process | awk '{print $17}'` 
processtotal=$(($utime+$stime+$cutime+$cstime)) 
diff_processtotal=$(($processtotal-$prev_processtotal)) 
diff_utime=$(($utime-$prev_utime)) 
processusage=$(($((1000*$(($diff_processtotal***4**))/$diff_total+5))/10)) 
clear 
echo "total cpu usage: $usage%" 
echo "one selected process: $processusage%" 
prev_total=$total 
prev_idle=$idle 
prev_processtotal=$processtotal 
prev_utime=$utime 
sleep 1 
done 

我有一個四核和事實證明,我不得不乘值由4太... 現在的問題解決;)