1

I need a command that would echo the average CPU usage over the past 10 seconds in Ubuntu 18.

Each of the following conditions must be met:

  1. It must be lightweight with a very small footprint, running a background script constantly writing to the filesystem is a no no.
  2. The value must account for number of cores automatically (I don't know the number of cores prior).
  3. The value must be a number between 0 and 1. There shouldn't be any other output as it will be read by a script, not a human. Alternatively suggest a robust algorithm of parsing the output of the suggested command, whatever it is.
  4. sudo requirement is fine, but the script must be able to be run as a command over SSH and it must have a proper process return behavior (0 exit code for success).

Built-in commands and untilities are preferred, but additional software is OK too as long as it's available in the official repos.

10
  • When you say average, how many samples are you willing to take in ten seconds? Apr 9, 2019 at 16:40
  • The more the better, but I think one each 1-3 seconds is fine. Apr 9, 2019 at 16:54
  • Just to be clear: you want to have just one command line or a script ?
    – Paradox
    Apr 9, 2019 at 18:05
  • You could start with this, then create a simple shell script to execute it periodically with sleep periods in between.
    – Seamus
    Apr 9, 2019 at 19:41
  • @Seamus I wanted to avoid that approach.. Apr 10, 2019 at 7:16

1 Answer 1

4

The sysstat package provides sar, a system activity data collector.

sar -u ALL 10 1

posts average cpu stats of the next 10 seconds since starting the command. The output is like

Linux 5(...)    11/05/21        _x86_64_        (1 CPU)

17:22:35        CPU     %user     %nice   %system   %iowait    %steal     %idle
17:22:36        all      8.85     20.75      2.46      0.00      0.00     67.94
Average:        all      8.85     20.75      2.46      0.00      0.00     67.94
1
  • It's a very old question and I no longer need a solution, but yours is a nice one nonetheless! Nov 6, 2021 at 19:08

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .