Search code examples
phpserver-load

How do you calculate server load in PHP?


How do you calculate the server load of PHP/apache? I know in vBulletin forums there's the server load displayed like 0.03 0.01 0.04 but it's not really understandable to a average joe. So I thought about a 1-100 percentile scale. I wanted to display a server load visual that reads from a DIV:

$load = $serverLoad*100;
<div class=\"serverLoad\">
    <div style=\"width: $load%;\"></div>//show visual for server load on a 1-100 % scale
</div>
<p>Current server load is $load%</p>
</div>

However, I don't know how to detect server load. Is it possible to do turn this server load into a percentile scale? I don't know where to start. May someone please help me out?

Thanks.


Solution

  • I have a very old function that should still do the trick:

    function getServerLoad($windows = false){
        $os=strtolower(PHP_OS);
        if(strpos($os, 'win') === false){
            if(file_exists('/proc/loadavg')){
                $load = file_get_contents('/proc/loadavg');
                $load = explode(' ', $load, 1);
                $load = $load[0];
            }elseif(function_exists('shell_exec')){
                $load = explode(' ', `uptime`);
                $load = $load[count($load)-1];
            }else{
                return false;
            }
    
            if(function_exists('shell_exec'))
                $cpu_count = shell_exec('cat /proc/cpuinfo | grep processor | wc -l');        
    
            return array('load'=>$load, 'procs'=>$cpu_count);
        }elseif($windows){
            if(class_exists('COM')){
                $wmi=new COM('WinMgmts:\\\\.');
                $cpus=$wmi->InstancesOf('Win32_Processor');
                $load=0;
                $cpu_count=0;
                if(version_compare('4.50.0', PHP_VERSION) == 1){
                    while($cpu = $cpus->Next()){
                        $load += $cpu->LoadPercentage;
                        $cpu_count++;
                    }
                }else{
                    foreach($cpus as $cpu){
                        $load += $cpu->LoadPercentage;
                        $cpu_count++;
                    }
                }
                return array('load'=>$load, 'procs'=>$cpu_count);
            }
            return false;
        }
        return false;
    }
    

    This returns processor load. You can also use memory_get_usage and memory_get_peak_usage for memory load.

    If you can't handle finding percentages based on this... sigh, just post and we'll try together.