您所在地位置:首页> / PHP / PHP运用 / >正文

PHP代码获取当前系统的CPU和内存的空闲百分比

2012-06-07 09:44:03 分类:PHP运用 阅读(1803) 加入收藏

设想我们有一个php页面A比较耗资源,因此在每次执行页面A中的代码前需要检测一下系统目前CPU和内存的空闲百分比。
我们可以利用下面几个函数来解决这个问题

//获取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(); 
};

 

上一篇:工作中写的一段mysql存储过程

下一篇:Windows下的Memcache安装与配置