Question

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

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top