How to Check System Load in Php on Linux

By | August 8, 2020

System load

System load is a measure of how busy the system is running the processes. Higher system load simply means more processes are running and more are waiting to be run.

When coding php applications, it sometimes is useful or necessary to find the current load on the server/system.

For example if you want to run a long resource intensive task like database operation, then you may wan't to first ensure that system load is low enough for the task to run without causing system availability issues.

In php there are a number of ways to check the system load or the load on your web server.

Note that these are for linux only. They do not apply to windows.

Method 1 - /proc/loadavg

The first method is to read the /proc/loadavg file on linux. It outputs the load averages.

echo file_get_contents('/proc/loadavg');

It basically shows the content of the file /proc/loadavg. It can be checked from terminal/shell like this

$ cat /proc/loadavg

Output :
0.04 0.08 0.11 1/381 3584

There are 5 fields.
1. Average load on server in past 1 minute.
2. Average load on server in past 5 minutes.
3. Averate load on server in past 10 minutes.
4. Running processes/Total processes
5. Last process id that ran.

Method 2 - uptime

Another way to get the system load is by running the uptime system command.

$uptime = shell_exec("uptime");
echo "$uptime";

Output is :

11:51:23 up 34 min,  2 users,  load average: 0.00, 0.01, 0.06

The last 3 numbers after load average are same as the first 3 numbers of the proc/loadavg output.

Method 3 - sys_getloadavg

Php as of version 5.1.3 has an inbuilt function called sys_getloadavg that can be directly used to get the load parameters.

It is the simplest method and does not require any system calls.

Returns three samples representing the average system load (the number of processes in the system run queue) over the last 1, 5 and 15 minutes, respectively.
print_r(sys_getloadavg());
Array
(
    [0] => 0.51
    [1] => 0.26
    [2] => 0.16
)

Thats values in the array are the loads in the past 1, 5 and 15 minutes respectively.

Resources

For a better explanation of CPU load check this wikipedia article
http://en.wikipedia.org/wiki/Load_(computing)

About Silver Moon

A Tech Enthusiast, Blogger, Linux Fan and a Software Developer. Writes about Computer hardware, Linux and Open Source software and coding in Python, Php and Javascript. He can be reached at [email protected].

3 Comments

How to Check System Load in Php on Linux
  1. Navnath

    hello

    has anyone tried gphoto2 commands in the php

    my php

    its working fine in terminal but when i run in localhost its doest not excute

  2. Raphi

    Just what I needed! wrapped a bash-script around to check in intervalls, so now I’ve got a quick and easy way to keep track of the serverload. Thanks! :-D

Leave a Reply

Your email address will not be published. Required fields are marked *