【问题标题】:How do you calculate server load in PHP?您如何计算 PHP 中的服务器负载?
【发布时间】:2011-04-07 23:01:00
【问题描述】:

PHP/apache的服务器负载如何计算?我知道在 vBulletin 论坛中,服务器负载显示为 0.03 0.01 0.04,但对于普通的 joe 来说,这并不是真正可以理解的。所以我想到了一个 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>

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

谢谢。

【问题讨论】:

  • 这三个值存在的原因是单个百分比指标并不能真正告诉您任何事情。

标签: php server-load


【解决方案1】:

我有一个非常古老的函数,它仍然可以解决问题:

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 进行内存加载。

如果您无法处理基于此的百分比查找...叹息,请发布,我们将一起尝试。

【讨论】:

    【解决方案2】:

    PHP 中的这个函数可能会做到这一点:sys_getloadavg()

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

    【讨论】:

      【解决方案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;
      }
      

      【讨论】:

        【解决方案4】:

        如果“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];
        }
        

        【讨论】:

          【解决方案5】:
          <?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.');
          }
          ?>
          

          【讨论】:

          • 虽然这段代码 sn-p 可以解决问题,including an explanation 确实有助于提高您的帖子质量。请记住,您正在为将来的读者回答问题,而这些人可能不知道您的代码建议的原因。 - From review
          • 感激!感谢您的指导,一定会记住的
          【解决方案6】:

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

          print_r(sys_getloadavg());
          

          输出:数组([0] => 0 [1] => 0.01 [2] => 0.05)

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

          【讨论】:

            【解决方案7】:

            这是一个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;
            }
            

            【讨论】:

              【解决方案8】:
              function _loadavg()
              {
                  if(class_exists("COM")) 
                  {
                    $wmi = new COM("WinMgmts:\\\\.");
                    $cpus = $wmi->InstancesOf("Win32_Processor");
              
                    foreach ($cpus as $cpu) 
                    {
                     return $cpu->LoadPercentage;
                    }
                  } 
              }
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 2021-11-05
                • 2014-07-05
                • 1970-01-01
                • 2012-01-15
                • 1970-01-01
                • 2017-02-12
                • 1970-01-01
                相关资源
                最近更新 更多