当前系统的CPU和内存的空闲百分比
设想我们有一个php页面A比较耗资源,因此在每次执行页面A中的代码前需要检测一下系统目前CPU和内存的空闲百分比。
我们可以利用下面几个函数来解决这个问题
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
//获取cpu的空闲百分比
function get_cpufree(){
$cmd = "top -n 1 -b -d 0.1 | grep 'Cpu'";//调用top命令和grep命令
$lastline = exec($cmd,$output);
preg_match('/(\S+)%id/',$lastline, $matches);//正则表达式获取cpu空闲百分比
$cpufree = $matches[1];
return $cpufree;
}
//获取内存空闲百分比
function get_memfree(){
$cmd = 'free -m';//调用free命令
$lastline = exec($cmd,$output);
preg_match('/Mem:\s+(\d+)/',$output[1], $matches);
$memtotal = $matches[1];
preg_match('/(\d+)$/',$output[2], $matches);
$memfree = $matches[1]*100.0/$memtotal;
return $memfree;
}
//获取某个程序当前的进程数
function get_proc_count($name){
$cmd = "ps -e";//调用ps命令
$output = shell_exec($cmd);
$result = substr_count($output, ' '.$name);
return $result;
}
|
比如当CPU空闲率小于30%时我们延迟页面A执行:
1 2 3 4 5 6 7 |
$cpufree = get_cpufree();
while( $cpufree<30 ){
// wait for 0.1 seconds
usleep(0.1*1000000);
$cpufree = get_cpufree();
};
|

浙公网安备 33010602011771号