你如何计算PHP中的服务器负载?

时间:2011-04-07 23:01:01

标签: php server-load

如何计算PHP / apache的服务器负载?我知道在vBulletin论坛中,服务器负载显示为0.03 0.01 0.04,但对于一般的乔来说,这是不可理解的。所以我想到了1-100百分位的规模。我想显示一个从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>

但是,我不知道如何检测服务器负载。是否可以将此服务器负载转换为百分位数?我不知道从哪里开始。愿有人请帮帮我吗?

感谢。

8 个答案:

答案 0 :(得分:14)

我有一个非常古老的功能,应该仍然可以做到这一点:

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;
}

这会返回处理器负载。您还可以使用memory_get_usagememory_get_peak_usage进行内存加载。

如果您无法根据此信息找到百分比...叹息,请发帖,我们将一起尝试。

答案 1 :(得分:9)

PHP中的这个功能可以做到这一点:sys_getloadavg()

返回三个样本,分别代表过去1分钟,5分钟和15分钟内的平均系统负载(系统运行队列中的进程数)。

答案 2 :(得分:3)

function get_server_load()
{

    $serverload = array();

    // DIRECTORY_SEPARATOR checks if running windows
    if(DIRECTORY_SEPARATOR != '\\')
    {
        if(function_exists("sys_getloadavg"))
        {
            // sys_getloadavg() will return an array with [0] being load within the last minute.
            $serverload = sys_getloadavg();
            $serverload[0] = round($serverload[0], 4);
        }
        else if(@file_exists("/proc/loadavg") && $load = @file_get_contents("/proc/loadavg"))
        {
            $serverload = explode(" ", $load);
            $serverload[0] = round($serverload[0], 4);
        }
        if(!is_numeric($serverload[0]))
        {
            if(@ini_get('safe_mode') == 'On')
            {
                return "Unknown";
            }

            // Suhosin likes to throw a warning if exec is disabled then die - weird
            if($func_blacklist = @ini_get('suhosin.executor.func.blacklist'))
            {
                if(strpos(",".$func_blacklist.",", 'exec') !== false)
                {
                    return "Unknown";
                }
            }
            // PHP disabled functions?
            if($func_blacklist = @ini_get('disable_functions'))
            {
                if(strpos(",".$func_blacklist.",", 'exec') !== false)
                {
                    return "Unknown";
                }
            }

            $load = @exec("uptime");
            $load = explode("load average: ", $load);
            $serverload = explode(",", $load[1]);
            if(!is_array($serverload))
            {
                return "Unknown";
            }
        }
    }
    else
    {
        return "Unknown";
    }

    $returnload = trim($serverload[0]);

    return $returnload;
}

答案 3 :(得分:1)

如果“exec”被激活

/**
 * Return the current server load
 * It needs "exec" activated
 *
 * e.g.
 * 15:06:37 up 10 days,  5:59, 12 users,  load average: 1.40, 1.45, 1.33
 * returns
 * float(1.40)
 */
public function getServerLoad()
{
    preg_match('#(\d\.\d+),[\d\s\.]+,[\d\s\.]+$#', exec("uptime"), $m);
    return (float)$m[1];
}

答案 4 :(得分:1)

<?php
$load = sys_getloadavg();
if ($load[0] > 0.80) {
    header('HTTP/1.1 503 Too busy, try again later');
    die('Server too busy. Please try again later.');
}
?>

答案 5 :(得分:0)

如果你有适当的权限,它在LAMP环境中非常容易,

print_r(sys_getloadavg());
  

输出:数组([0] =&gt; 0 [1] =&gt; 0.01 [2] =&gt; 0.05)

数组值分别是过去1,5和15分钟的平均负载。

答案 6 :(得分:0)

这是一个兼容windows / linux的php服务器加载功能:

function get_server_load() {
    $load = '';
    if (stristr(PHP_OS, 'win')) {
        $cmd = 'wmic cpu get loadpercentage /all';
        @exec($cmd, $output);
        if ($output) {
            foreach($output as $line) {
                if ($line && preg_match('/^[0-9]+$/', $line)) {
                    $load = $line;
                    break;
                }
            }
        }

    } else {
        $sys_load = sys_getloadavg();
        $load = $sys_load[0];
    }
    return $load;
}

答案 7 :(得分:-1)

function _loadavg()
{
    if(class_exists("COM")) 
    {
      $wmi = new COM("WinMgmts:\\\\.");
      $cpus = $wmi->InstancesOf("Win32_Processor");

      foreach ($cpus as $cpu) 
      {
       return $cpu->LoadPercentage;
      }
    } 
}