top command first iteration always returns the same result

后端 未结 5 853
故里飘歌
故里飘歌 2021-01-12 16:12

When running top -b -n 1, the command always returns the same CPU values. Consider the following test run 5 times in succession:

[user@server ~]$ top -b -n          


        
相关标签:
5条回答
  • 2021-01-12 16:21

    CPU utilisation figures are calculated as an average over a time interval. For the first iteration, that time interval is "from system boot until now"; for subsequent iterations, the time interval is "from the last iteration until now".

    0 讨论(0)
  • 2021-01-12 16:25

    if anyone is looking for a one line get the value of cpu then try this

    top -b -n 5 -d.2 | grep "Cpu" | tail -n1 | awk '{print($2)}' | cut -d'%' -f 1

    0 讨论(0)
  • 2021-01-12 16:38

    Here's an example to computes total CPU usage for ALL processes in top. I use -d flag to increase the default interval in order to smooth out the value. Not using tail because the header can be specific to Linux distribution.

    top -b -d 5 -n 2 | awk '$1 == "PID" {block_num++; next} block_num == 2 {sum += $9;} END {print sum}'
    
    0 讨论(0)
  • 2021-01-12 16:42

    Top doesn't know what process time counts were before it starts, so it makes a guess in the first pass, based on a variety of factors like load average and waiting threads.

    You can see the same effect if you start top interactively and quickly examine the first batch of results it returns.

    Simple solution: top -b -n 5 -d.2 | grep "Cpu(s)" | tail -n+2

    0 讨论(0)
  • 2021-01-12 16:45

    I ran into this issue as well and did some digging.

    If you 'man top' and scroll waaaay down, you'll find the following from section 7 . . .

    The top command calculates Cpu(s) by looking at the change in CPU time values between samples. When you first run it, it has no previous sample to compare to, so these initial values are the percentages since boot. It means you need at least two loops or you have to ignore summary output from the first loop. This is problem for example for batch mode. There is a possible workaround if you define the CPULOOP=1 environment variable. The top command will be run one extra hidden loop for CPU data before standard output.

    Hope this helps!

    0 讨论(0)
提交回复
热议问题