以下代码适用于linux/freebsd环境下查看内存与Cpu使用情况。
代码如下:
<?php
/*
@系统参数探测 LINUX
@Edit www.
@date 2013/5/8
*/
function sys_linux()
{
// CPU
if (false === ($str = @file(“/proc/cpuinfo”))) return false;
$str = implode(“”, $str);
@preg_match_all(“/model\s+name\s{0,}\:+\s{0,}([\w\s\)\(.]+)[\r\n]+/”, $str, $model);
//@preg_match_all(“/cpu\s+MHz\s{0,}\:+\s{0,}([\d\.]+)[\r\n]+/”, $str, $mhz);
@preg_match_all(“/cache\s+size\s{0,}\:+\s{0,}([\d\.]+\s{0,}[A-Z]+[\r\n]+)/”, $str, $cache);
if (false !== is_array($model[1]))
{
$res['cpu']['num'] = sizeof($model[1]);
for($i = 0; $i < $res['cpu']['num']; $i++)
{
$res['cpu']['detail'][] = “类型:”.$model[1][$i].” 缓存:”.$cache[1][$i];
}
if (false !== is_array($res['cpu']['detail'])) $res['cpu']['detail'] = implode(”
“, $res['cpu']['detail']);
}
// UPTIME
if (false === ($str = @file(“/proc/uptime”))) return false;
$str = explode()(” “, implode(“”, $str));
$str = trim($str[0]);
$min = $str / 60;
$hours = $min / 60;
$days = floor($hours / 24);
$hours = floor($hours – ($days * 24));
$min = floor($min – ($days * 60 * 24) – ($hours * 60));
if ($days !== 0) $res['uptime'] = $days.”天”;
if ($hours !== 0) $res['uptime'] .= $hours.”小时”;
$res['uptime'] .= $min.”分钟”;
// MEMORY
if (false === ($str = @file(“/proc/meminfo”))) return false;
$str = implode(“”, $str);
preg_match_all(“/MemTotal\s{0,}\:+\s{0,}([\d\.]+).+?MemFree\s{0,}\:+\s{0,}([\d\.]+).+?SwapTotal\s{0,}\:+\s{0,}([\d\.]+).+?SwapFree\s{0,}\:+\s{0,}([\d\.]+)/s”, $str, $buf);
$res['memTotal'] = round($buf[1][0]/1024, 2);
$res['memFree'] = round($buf[2][0]/1024, 2);
$res['memUsed'] = ($res['memTotal']-$res['memFree']);
$res['memPercent'] = (floatval($res['memTotal'])!=0)?round(($res['memUsed']/$res['memTotal'])*90,2):0;
$res['swapTotal'] = round($buf[3][0]/1024, 2);
$res['swapFree'] = round($buf[4][0]/1024, 2);
$res['swapUsed'] = ($res['swapTotal']-$res['swapFree']);
$res['swapPercent'] = (floatval($res['swapTotal'])!=0)?round(($res['swapUsed']/$res['swapTotal'])*90,2):0;
// LOAD AVG
if (false === ($str = @file(“/proc/loadavg”))) return false;
$str = explode(” “, implode(“”, $str));
$str = array_chunk($str, 3);
$res['loadAvg'] = implode(” “, $str[0]);
return $res;
}
/*
系统参数探测 FreeBSD
*/
function sys_freebsd()
{
//CPU
if (false === ($res['cpu']['num'] = get_key(“hw.ncpu”))) return false;
$res['cpu']['detail'] = get_key(“hw.model”);
//LOAD AVG
if (false === ($res['loadAvg'] = get_key(“vm.loadavg”))) return false;
$res['loadAvg'] = str_replace()(“{“, “”, $res['loadAvg']);
$res['loadAvg'] = str_replace(“}”, “”, $res['loadAvg']);
//UPTIME
if (false === ($buf = get_key(“kern.boottime”))) return false;
$buf = explode(‘ ‘, $buf);
$sys_ticks = time() – intval($buf[3]);
$min = $sys_ticks / 60;
$hours = $min / 60;
$days = floor($hours / 24);
$hours = floor($hours – ($days * 24));
$min = floor($min – ($days * 60 * 24) – ($hours * 60));
if ($days !== 0) $res['uptime'] = $days.”天”;
if ($hours !== 0) $res['uptime'] .= $hours.”小时”;
$res['uptime'] .= $min.”分钟”;
//MEMORY
if (false === ($buf = get_key(“hw.physmem”))) return false;
$res['memTotal'] = round($buf/1024/1024, 2);
$buf = explode(“\n”, do_command(“vmstat”, “”));
$buf = explode(” “, trim($buf[2]));
$res['memFree'] = round($buf[5]/1024, 2);
$res['memUsed'] = ($res['memTotal']-$res['memFree']);
$res['memPercent'] = (floatval($res['memTotal'])!=0)?round(($res['memUsed']/$res['memTotal'])*90,2):0;
$buf = explode(“\n”, do_command(“swapinfo”, “-k”));
$buf = $buf[1];
preg_match_all(“/([0-9]+)\s+([0-9]+)\s+([0-9]+)/”, $buf, $bufArr);
$res['swapTotal'] = round($bufArr[1][0]/1024, 2);
$res['swapUsed'] = round($bufArr[2][0]/1024, 2);
$res['swapFree'] = round($bufArr[3][0]/1024, 2);
$res['swapPercent'] = (floatval($res['swapTotal'])!=0)?round(($res['swapUsed']/$res['swapTotal'])*90,2):0;
return $res;
}
/*
取得参数值 FreeBSD
*/
function get_key($keyName)
{
return do_command(‘sysctl’, “-n $keyName”);
}
/*
确定执行文件位置 FreeBSD
*/
function find_command($commandName)
{
$path = array(‘/bin’, ‘/sbin’, ‘/usr/bin’, ‘/usr/sbin’, ‘/usr/local/bin’, ‘/usr/local/sbin’);
foreach($path as $p)
{
if (@is_executable(“$p/$commandName”)) return “$p/$commandName”;
}
return false;
}
/*
执行系统命令 FreeBSD
*/
function do_command($commandName, $args)
{
$buffer = “”;
if (false === ($command = find_command($commandName))) return false;
if ($fp = @popen(“$command $args”, ‘r’))
{
while (!@feof($fp))
{
$buffer .= @fgets($fp, 4096);
}
return trim($buffer);
}
return false;
}
?>
说明:
memory用此函数可搞定: memory_get_usage()
在Windows下面只能读取cmd命令运行的结果。
例如:
$a = system(‘mem’);
echo $a.”
“;
//或者
$a = system(‘mem’);
echo $a.”
“;
?>
您可能感兴趣的文章:
php获取CPU使用情况的代码
php中使用proc/loadavg监控CPU的平均负载
php记录服务器负载、内存、cpu状态的代码
php页面缓存的例子(减经cpu与mysql负担)
php获取linux服务器CPU、内存、硬盘使用率的实现代码
php获取计算机唯一标识信息(cpu,网卡,MAC地址)的代码
PHP-CGI 进程 CPU 100% 与 file_get_contents 函数的关系
php程序随机记录mysql rand()造成CPU 100%的解决方法
php获取CPU使用信息
1、数据库配置文件: conn.php
define("MONITORED_IP", "172.16.0.191"); //被监控的服务器IP地址 也就是本机地址
define("DB_SERVER", "172.16.7.2"); //存放数据的服务器IP地址
define("DB_USER", "root");
define("DB_PWD","111111");
define("DB_NMAE","performance");
class MyConnect{
public function connect($db_server,$db_user,$db_pwd,$db_name){
$conn = mysql_connect()($db_server,$db_user,$db_pwd);
if (!$conn){
die('连接数据库失败: ' . mysql_error());
}
$flag = mysql_select_db($db_name,$conn);
if(!$flag){
echo "<p align='center'>数据库连接出错!</p>";exit();
}else{
mysql_query()("SET NAMES UTF8");
}
}
}
?>
2、获取服务器性能数据的文件 get_used_status.php
<?php
/**
* 获取服务器性能CPU、内存、硬盘等使用率
* Edit www.
*/
/*连接数据 begin*/
include("conn.php");
$obj_MyConnect = new MyConnect();
$obj_MyConnect -> connect(DB_SERVER,DB_USER,DB_PWD,DB_NMAE);
/*连接数据 end*/
function get_used_status(){
$fp = popen('top -b -n 2 | grep -E "^(Cpu|Mem|Tasks)"',"r");//获取某一时刻系统cpu和内存使用情况
$rs = "";
while(!feof($fp)){
$rs .= fread($fp,1024);
}
pclose($fp);
$sys_info = explode()("\n",$rs);
$tast_info = explode(",",$sys_info[3]);//进程 数组
$cpu_info = explode(",",$sys_info[4]); //CPU占有量 数组
$mem_info = explode(",",$sys_info[5]); //内存占有量 数组
//正在运行的进程数
$tast_running = trim(trim($tast_info[1],'running'));
//CPU占有量
$cpu_usage = trim(trim($cpu_info[0],'Cpu(s): '),'%us'); //百分比
//内存占有量
$mem_total = trim(trim($mem_info[0],'Mem: '),'k total');
$mem_used = trim($mem_info[1],'k used');
$mem_usage = round(100*intval($mem_used)/intval($mem_total),2); //百分比
/*硬盘使用率 begin*/
$fp = popen('df -lh | grep -E "^(/)"',"r");
$rs = fread($fp,1024);
pclose($fp);
$rs = preg_replace("/\s{2,}/",' ',$rs); //把多个空格换成 “_”
$hd = explode(" ",$rs);
$hd_avail = trim($hd[3],'G'); //磁盘可用空间大小 单位G
$hd_usage = trim($hd[4],'%'); //挂载点 百分比
//print_r($hd);
/*硬盘使用率 end*/
//检测时间
$fp = popen("date +\"%Y-%m-%d %H:%M\"","r");
$rs = fread($fp,1024);
pclose($fp);
$detection_time = trim($rs);
/*获取IP地址 begin*/
/*
$fp = popen('ifconfig eth0 | grep -E "(inet addr)"','r');
$rs = fread($fp,1024);
pclose($fp);
$rs = preg_replace("/\s{2,}/",' ',trim($rs)); //把多个空格换成 “_”
$rs = explode(" ",$rs);
$ip = trim($rs[1],'addr:');
*/
/*获取IP地址 end*/
/*
$file_name = "/tmp/data.txt"; // 绝对路径: homedata.dat
$file_pointer = fopen($file_name, "a+"); // "w"是一种模式,详见后面
fwrite($file_pointer,$ip); // 先把文件剪切为0字节大小, 然后写入
fclose($file_pointer); // 结束
*/
return array('cpu_usage'=>$cpu_usage,'mem_usage'=>$mem_usage,'hd_avail'=>$hd_avail,'hd_usage'=>$hd_usage,'tast_running'=>$tast_running,'detection_time'=>$detection_time);
}
//echo date("Y-m-d H:i:s",time())."<br>";
$status=get_used_status();
$sql = "insert into performance(ip,cpu_usage,mem_usage,hd_avail,hd_usage,tast_running,detection_time) ";
$sql .= " value('".MONITORED_IP."','".$status['cpu_usage']."','".$status['mem_usage']."','".$status['hd_avail']."','".$status['hd_usage']."','".$status['tast_running']."','".$status['detection_time']."')";
$query = mysql_query($sql) or die("SQL 语句执行失败!");
unset($status);
//echo date("Y-m-d H:i:s",time())."<br>";
?>
您可能感兴趣的文章:
php获取CPU使用情况的代码
php中使用proc/loadavg监控CPU的平均负载
php记录服务器负载、内存、cpu状态的代码
php页面缓存的例子(减经cpu与mysql负担)
php获取cpu与内存使用情况的代码一例
php获取计算机唯一标识信息(cpu,网卡,MAC地址)的代码
PHP-CGI 进程 CPU 100% 与 file_get_contents 函数的关系
php程序随机记录mysql rand()造成CPU 100%的解决方法
php获取CPU使用信息
完整代码如下:
<?php
/**
* 页面执行时间类
* Edit www.
* Date 2013/5/7
*/
class Timer
{
var starttime;//页面开始执行时间
var stoptime;//页面结束执行时间
var spendtime;//页面执行花费时间
function getmicrotime()//获取返回当前微秒数的浮点数
{
list(usec,sec)=explode()(" ",microtime());
return ((float)usec + (float)sec);
}
function start()//页面开始执行函数,返回开始页面执行的时间
{
this->starttime=this->getmicrotime();
}
function display()//显示页面执行的时间
{
this->stoptime=this->getmicrotime();
this->spendtime=this->stoptime-this->starttime;
return round(this->spendtime,10);
}
}
/*调用示例
timer=new Timer();
timer->start();
/*以下为要测试执行时间的程序代码
for(i=0;i<100000;i++)
{
echo i;
echo "<br>";
}
*/
echo "<p>以上代码执行时间为:".timer->display()."秒";
?>