Skip to content

sys_getloadavg()

This article covers the PHP sys_getloadavg() function, including an overview, how it works, and usage examples.

Introduction to the sys_getloadavg() function

The sys_getloadavg() function is a built-in PHP function that retrieves the system load average. Note that it is only available on Unix-like systems (Linux, macOS) and will not work on Windows. It can be used to monitor system performance and optimize resource allocation.

The sys_getloadavg() function takes no arguments and returns an array containing the 1, 5, and 15 minute load averages of the system.

How to use the sys_getloadavg() function

Using the sys_getloadavg() function is straightforward. It returns an array of load averages, which should be checked for length before accessing specific indices. Here is an example:

How to use the sys_getloadavg() function

php
<?php
$load = sys_getloadavg();
if (count($load) >= 3) {
    echo "1 minute load average: " . $load[0] . "\n";
    echo "5 minute load average: " . $load[1] . "\n";
    echo "15 minute load average: " . $load[2] . "\n";
} else {
    echo "Unable to retrieve load averages.\n";
}
?>

In this example, we call sys_getloadavg() and assign the returned array to $load. We verify the array contains at least three elements before outputting the 1, 5, and 15 minute load averages.

Performance considerations

The sys_getloadavg() function is a useful tool for monitoring system performance. However, it reads directly from the OS kernel and is not computationally expensive. In high-traffic web applications, it is still best practice to avoid calling it on every request to minimize unnecessary overhead. Use it for periodic monitoring or diagnostic checks rather than in tight loops or performance-critical sections.

Conclusion

In conclusion, sys_getloadavg() provides a quick way to retrieve system load averages on Unix-like systems. By using it responsibly and checking the returned array, you can effectively monitor system performance.

Practice

What is the purpose of the sys_getloadavg() function in PHP?

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.