top command's CPU usage calculation

送分小仙女□ 提交于 2019-12-10 13:56:44

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/552976/top-commands-cpu-usage-calculation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!