xhprof使用

//记录性能剖析
require_once(APPPATH.'/libraries/performance.class.php');
define('XHPROF_ENABLE',true);
define('XHPROF_LOG_DATA','/data/logs/xhprof/');
define('PERCENT',1);
performace::init();

<?php
/*
 * 性能剖析,静态类
 */
require_once(APPPATH.'/libraries/xhprof_lib.class.php');
require_once(APPPATH.'/libraries/xhprof_runs.class.php');
class performace
{
	private static $no_write = true;
	static public function init()
	{
		//如果设定为开启,则继续
		if(XHPROF_ENABLE == true && function_exists('xhprof_enable')){
			$percent = mt_rand(1,PERCENT);
			if($percent == 1){	//随机记录日志
				xhprof_enable(XHPROF_FLAGS_CPU + XHPROF_FLAGS_MEMORY);
				register_shutdown_function('performace::save');
			}
		}
	}

	static public function save()
	{
		$xhprof_data = xhprof_disable();
		
		$dir = ini_get("xhprof.output_dir") . $_SERVER['SCRIPT_NAME'];
		if (!file_exists($dir))
		{
			if (!mkdir($dir , 0777 , true)) return ;
		}
		$xhprof_runs = new XHProfRuns_Default($dir);
		$filename = $_REQUEST['c'].'_'.$_REQUEST['m'];
		$filename = $filename === '_'? null : $filename;
		
		//提取内存和执行时间
		foreach($xhprof_data as $key=>$PerformaceInfo)
		{
			$mu = $PerformaceInfo['mu']; //占用内存
			$wt = $PerformaceInfo['wt']; //占用时间
			$ct = $PerformaceInfo['ct']; //调用次数
			//对于超过一定阀值的进行日志记录
			$mu = $mu/1000000;
			if($mu > 30 && self::$no_write == true){	//内存占用大于30M
				$xhprof_runs->save_run($xhprof_data, 'xhprof',$filename);
				self::log("$key 的内存占用为 $mu MB");
				self::$no_write = false;
			}
			$wt = $wt/1000;
			if($wt > 1000 && self::$no_write == true){	//执行时间大于500ms
				$xhprof_runs->save_run($xhprof_data, 'xhprof',$filename);
				self::log("$key 的执行时间为 $wt ms");
				self::$no_write = false;
			}
			if($ct > 200 && self::$no_write == true){	//调用次数大于200
				$xhprof_runs->save_run($xhprof_data, 'xhprof',$filename);
				self::log("$key 的调用次数为 $ct");
				self::$no_write = false;
			}
		}
	}

	static public function log($msg)
	{
		$filename = XHPROF_LOG_DATA.date('Y-m-d').'.log';
		$current = date('Y-m-d H:i:s');
		$uri = $_SERVER['REQUEST_URI'];
		$LogContent = iconv("UTF-8","GBK","time:$current, url:$uri, msg:$msg\n");
		file_put_contents($filename,$LogContent, FILE_APPEND);
	}
}


你可能感兴趣的:(xhprof使用)