Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: wait until CPU usage gets below a threshold

In a bash script I need to wait until CPU usage gets below a threshold.

In other words, I'd need a command wait_until_cpu_low which I would use like this:

# Trigger some background CPU-heavy command
wait_until_cpu_low 40
# Some other commands executed when CPU usage is below 40%

How could I do that?

Edit:

  • target OS is: Red Hat Enterprise Linux Server release 6.5
  • I'm considering the average CPU usage (across all cores)
like image 453
sdabet Avatar asked Aug 31 '15 12:08

sdabet


1 Answers

A much more efficient version just calls mpstat and awk once each, and keeps them both running until done; no need to explicitly sleep and restart both processes every second (which, on an embedded platform, could add up to measurable overhead):

wait_until_cpu_low() {
    awk -v target="$1" '
    $13 ~ /^[0-9.]+$/ {
      current = 100 - $13
      if(current <= target) { exit(0); }
    }' < <(LC_ALL=C mpstat 1)
}

I'm using $13 here because that's where idle % is for my version of mpstat; substitute appropriately if yours differs.

This has the extra advantage of doing floating point math correctly, rather than needing to round to integers for shell-native math.

like image 181
Charles Duffy Avatar answered Sep 18 '22 01:09

Charles Duffy