php sys_getload,PHP sys_getloadavg 用法 手册 | 示例代码

Function to get current CPU load as percentage value under Windows and Linux.

Note: Function is getServerLoad(). It will return a decimal value as percentage of current CPU load or NULL if something went wrong (e. g. insufficient access rights).

header("Content-Type: text/plain");

function_getServerLoadLinuxData()

{

if (is_readable("/proc/stat"))

{$stats= @file_get_contents("/proc/stat");

if ($stats!==false)

{// Remove double spaces to make it easier to extract values with explode()$stats=preg_replace("/[[:blank:]]+/"," ",$stats);// Separate lines$stats=str_replace(array("rn","nr","r"),"n",$stats);$stats=explode("n",$stats);// Separate values and find line for main CPU loadforeach ($statsas$statLine)

{$statLineData=explode(" ",trim($statLine));// Found!if

(

(count($statLineData) >=5) &&

($statLineData[0] =="cpu")

)

{

return array($statLineData[1],$statLineData[2],$statLineData[3],$statLineData[4],

);

}

}

}

}

returnnull;

}// Returns server load in percent (just number, without percent sign)functiongetServerLoad()

{$load=null;

if (stristr(PHP_OS,"win"))

{$cmd="wmic cpu get loadpercentage /all";

@exec($cmd,$output);

if ($output)

{

foreach ($outputas$line)

{

if ($line&&preg_match("/^[0-9]+$/",$line))

{$load=$line;

break;

}

}

}

}

else

{

if (is_readable("/proc/stat"))

{// Collect 2 samples - each with 1 second period

// See: https://de.wikipedia.org/wiki/Load#Der_Load_Average_auf_Unix-Systemen$statData1=_getServerLoadLinuxData();sleep(1);$statData2=_getServerLoadLinuxData();

if

(

(!is_null($statData1)) &&

(!is_null($statData2))

)

{// Get difference$statData2[0] -=$statData1[0];$statData2[1] -=$statData1[1];$statData2[2] -=$statData1[2];$statData2[3] -=$statData1[3];// Sum up the 4 values for User, Nice, System and Idle and calculate

// the percentage of idle time (which is part of the 4 values!)$cpuTime=$statData2[0] +$statData2[1] +$statData2[2] +$statData2[3];// Invert percentage to get CPU time, not idle time$load=100- ($statData2[3] *100/$cpuTime);

}

}

}

return$load;

}//----------------------------$cpuLoad=getServerLoad();

if (is_null($cpuLoad)) {

echo"CPU load not estimateable (maybe too old Windows or missing rights at Linux or Windows)";

}

else {

echo$cpuLoad."%";

}?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值