Check system load in php on linux
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.
The first method is to read the /proc/loadavg file on linux. It outputs the load averages.
It basically shows the content of the file /proc/loadavg. It can be checked from terminal/shell like this
$ cat /proc/loadavg
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.
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.
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.51  => 0.26  => 0.16 )
Thats values in the array are the loads in the past 1, 5 and 15 minutes respectively.
For a better explanation of CPU load check this wikipedia article