Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

top command's CPU usage calculation

I am trying to use GNU coreutil top's formula for calculating CPU usages in percentage. But top is using some half_total, to calculate the percentage, which is adding 0.5 to the percentage.

In utils.c of top's source, the following line (at 3.8 beta1, it is in line number: 459): -

*out++ = (int)((*diffs++ * 1000 + half_total) / total_change);

This translates to : ( (*diffs++ * 1000) / total_change ) + 1/2 So, it always gives a number, which is: "10 times the percentage, plus 0.5". So if the percentage is x, it will return 10x+0.5.

Can anyone explain how is this average calculated? or at least some pointer where I can get the help?

PS: Why can't we just use (*diffs++/total_change) * 100 to get the required percentage?

Top's source code is located at: - http://downloads.sourceforge.net/unixtop/top-3.8beta1.tar.gz?modtime=1210117842&big_mirror=0

like image 457
Sabya Avatar asked Feb 16 '09 11:02

Sabya


People also ask

How CPU usage is calculated?

The calculated CPU time that is derived from the reported consumed CPU time divided by the reported available capacity is 50% (45 seconds divided by 90 seconds). The interactive utilization percentage is 17% (15 seconds divided by 90 seconds). The batch utilization percentage is 33% (30 seconds divided by 90 seconds).


1 Answers

This is the way to do rounding for integer values, because the division discards the fractional part.

When you add half the divisor this is equivalent to a floating point division and rounding up if the fractional part is 0.5 or greater.

like image 66
starblue Avatar answered Sep 23 '22 15:09

starblue