Skip to content

Core\Os::loadAverage

Core\Os::loadAverage(): array<float>

Returns how busy the machine is, as three numbers.

The numbers are averages over the last 1, 5 and 15 minutes. Each one counts the processes that are running or waiting to run. A number larger than Core\Os::cpuCount() means some processes are waiting for a core.

Windows does not keep a load average. There, this method throws a RuntimeError. A program that must run on every system catches that error and decides what to do without the numbers.

The examples show how to read the three numbers, how to handle a system with no load average, and how to wait before a large job when the machine is busy.

Return value

Returns array<float>. Three floats: the averages over 1, 5 and 15 minutes, in that order.

Errors

  • RuntimeErrorWindows does not keep a load average, so this method throws there. The message names the platform.

Examples

The three averages

<?nvs
// Shows how to read how busy the machine is. This example runs on Linux and
// macOS only, because Windows does not keep a load average.
// requires: unix
array<float> $load = Core\Os::loadAverage();
// The array has three numbers: the averages over 1, 5 and 15 minutes.
// This prints `3`.
echo Core\Arr::count($load), "\n";
// A load average is never below 0. This prints `yes`.
echo $load[0] >= 0.0 && $load[1] >= 0.0 && $load[2] >= 0.0 ? 'yes' : 'no', "\n";
Output
3
yes

A machine with no load average

<?nvs
// Shows how a program runs on every system, including one with no load average.
// On Windows, `Core\Os::loadAverage` throws a `RuntimeError`.
class Load
{
// Returns the average over the last minute. It returns `null` when the
// machine does not keep a load average.
public static function lastMinute(): ?float
{
try {
return Core\Os::loadAverage()[0];
} catch (RuntimeError $error) {
return null;
}
}
}
?float $load = Load::lastMinute();
// On Linux and macOS the result is a number. On Windows it is `null`, and
// `?? 0.0` replaces it with 0. This prints `yes` on every system.
echo ($load ?? 0.0) >= 0.0 ? 'yes' : 'no', "\n";
Output
yes

Waiting when the machine is busy

<?nvs
// Shows how a program checks if the machine is too busy before it starts a
// large job, such as a report that runs every night.
class Machine
{
// The average over the last minute is divided by the number of cores.
// A result above 1.0 means some processes are waiting for a core.
public static function isBusy(): bool
{
try {
float $load = Core\Os::loadAverage()[0];
return $load / (Core\Os::cpuCount() as float) > 1.0;
} catch (RuntimeError $error) {
// Windows does not keep a load average, so the job starts.
return false;
}
}
}
string $plan = Machine::isBusy() ? 'wait' : 'start';
// The plan depends on how busy the machine is right now. It is always one of
// the two words, so this prints `yes`.
echo $plan == 'start' || $plan == 'wait' ? 'yes' : 'no', "\n";
Output
yes