CPU usage in top batch mode
Asked Answered
S

2

12

I have a problem that makes me mad. I am running top in batch mode with the following command,

top -b -n 1

The problem is I can run top in batch mode 100 times but the CPU usage never changes past the original value. The memory usage changes as expected but CPU stays the same. If I simultaneously run another top in a different window the CPU usage is changing for that top but not for the top in batch mode.

Basically CPU stats don't seem to change in batch mode and do in interactive mode. Does anyone know why? Try it yourself, run the above command a few times and observe the CPU usage staying the same then run top in interactive mode and observe the CPU usage constantly changing.

Suspiration answered 1/12, 2010 at 14:53 Comment(3)
Works fine here, otherwise you can use ps or perhaps sar | tail -1Preacher
I see the same behavior. The batch command must not run long enough to get good accumulators for CPU usage, or something.Timaru
Aschepler, It seems that is the case but I have not seen this mentioned anywhere else. If you set the iterations to 2 it works. The problem is I need it to work for 1 iteration.Suspiration
G
7

On the first iteration, it is showing you the average CPU usage since system startup.

(Note that this is no longer the case for newer versions of top).

Grube answered 3/12, 2010 at 4:11 Comment(1)
Yes, this seems to be the case.Suspiration
I
5

Here's one liner that displays cumulative CPU usage over a longer period of time, 5 seconds in this case. You can adjust it with -d flag.

top -b -d 5 -n 2 | awk '$1 == "PID" {block_num++; next} block_num == 2 {sum += $9;} END {print sum}'
Inanition answered 23/7, 2015 at 10:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.