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.

toc777
  • 2,607
  • 2
  • 26
  • 37
  • Works fine here, otherwise you can use `ps` or perhaps `sar | tail -1` – Anders Dec 01 '10 at 14:57
  • I see the same behavior. The batch command must not run long enough to get good accumulators for CPU usage, or something. – aschepler Dec 01 '10 at 15:34
  • 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. – toc777 Dec 01 '10 at 17:20

2 Answers2

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).

caf
  • 233,326
  • 40
  • 323
  • 462
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}'
Sergei Rodionov
  • 4,079
  • 6
  • 27
  • 44