# CPU statistics calculation algorithm

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 ?

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

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%
``````