Top CPU Usage Calculation Command

I am trying to use the GNU coreutil top formula to calculate CPU usage as a percentage. But the top uses half_total to calculate the percentage, which adds 0.5 to the percentage.

In utils.c above source , the following line (at 3.8 beta1, it is located at line: 459): -

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

This means: ((* diffs ++ * 1000) / total_change) + 1/2 Thus, it always gives a number that is equal to: "10 times more, plus 0.5". Therefore, if the percentage is x, it will return 10x + 0.5.

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

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

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

+6
linux cpu top-command gnu-coreutils
Feb 16 '09 at 11:14
source share
1 answer

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

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

+6
Feb 16 '09 at 11:18
source share



All Articles