我们可以利用下面几个函数来解决这个问题
//获取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执行:
$cpufree = get_cpufree();
while( $cpufree<30 ){
// wait for 0.1 seconds
usleep(0.1*1000000);
$cpufree = get_cpufree();
};
没有评论:
发表评论