top command's CPU usage calculation
Asked Answered
A

1

6

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

Albertson answered 16/2, 2009 at 11:14 Comment(0)
I
6

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.

Ize answered 16/2, 2009 at 11:18 Comment(2)
but what about the "10x" part?Albertson
Because the value is in tenths of a percent.Ize

© 2022 - 2024 — McMap. All rights reserved.