1

I too many search on internet to found algorithm calculated %Us , %Sy , %Id , ... on result of top command . but can not found any documentation .
some documents like this or this calculate cpu utilization but output not equal with output of top command . (too diff !!!)

How do the top or mpstat commands calculate cpu statistics ?

1

I calculate with this formula :

result=(CurrentUse-PrevUse)*100/(CurrentTotal-PrevTotal)

this is a example script calculate [us,sys,idle] of cpu .

#!/bin/bash 

prev_total=0 
prev_idle=0
prev_us=0
prev_sys=0

while true
do
        line=$(head -n1 /proc/stat)

        us=$(echo $line | awk '{print $2}') 
        ni=$(echo $line | awk '{print $3}') 
        sy=$(echo $line | awk '{print $4}') 
        id=$(echo $line | awk '{print $5}') 
        io=$(echo $line | awk '{print $6}') 
        irq=$(echo $line | awk '{print $7}') 
        si=$(echo $line | awk '{print $8}') 
        st=$(echo $line | awk '{print $9}') 
        g=$(echo $line | awk '{print $10}') 
        gn=$(echo $line | awk '{print $11}') 

        total=$(expr $us + $ni + $sy + $id + $io + $irq + $si + $st + $g + $gn) 

        let "diff_total=$total-$prev_total"
        let "diff_idle=$id-$prev_idle"
        let "diff_us=$us-$prev_us"
        let "diff_sys=$sy-$prev_sys"

         let "result_us=$diff_us * 100 / $diff_total" 
         let "result_idle=$diff_idle * 100 / $diff_total" 
         let "result_sys=$diff_sys * 100 / $diff_total" 

         echo -en "\rCpu   us:$result_us%  sys:$result_sys%  idle:$result_idle%\b\b"

        prev_total=$total 
        prev_idle=$id
        prev_us=$us
        prev_sys=$sy
        sleep 1
done

output like this :

Cpu   us:1%  sys:0%  idle:97%

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.