Benchmark.php----基准测试类
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class CI_Benchmark { var $marker = array(); //设置标记 function mark($name) { $this->marker[$name] = microtime(); } //计算时间 function elapsed_time($point1 = '', $point2 = '', $decimals = 4) { if ($point1 == '') { return '{elapsed_time}'; } if ( ! isset($this->marker[$point1])) { return ''; } if ( ! isset($this->marker[$point2])) { $this->marker[$point2] = microtime(); } list($sm, $ss) = explode(' ', $this->marker[$point1]); list($em, $es) = explode(' ', $this->marker[$point2]); return number_format(($em + $es) - ($sm + $ss), $decimals); } //计算内存 function memory_usage() { return '{memory_usage}'; } }测试基准类可以在 控制器, 视图,或者 模型.中使用,用法如下:
$this->benchmark->mark('code_start'); // Some code happens here $this->benchmark->mark('code_end'); echo $this->benchmark->elapsed_time('code_start', 'code_end');
$this->benchmark->mark('dog'); // Some code happens here $this->benchmark->mark('cat'); // More code happens here $this->benchmark->mark('bird'); echo $this->benchmark->elapsed_time('dog', 'cat'); echo $this->benchmark->elapsed_time('cat', 'bird'); echo $this->benchmark->elapsed_time('dog', 'bird');
$this->benchmark->mark('my_mark_start'); // Some code happens here... $this->benchmark->mark('my_mark_end'); $this->benchmark->mark('another_mark_start'); // Some more code happens here... $this->benchmark->mark('another_mark_end');
在CodeIgniter.php中的标记点:
$BM =& load_class('Benchmark', 'core'); $BM->mark('total_execution_time_start'); $BM->mark('loading_time:_base_classes_start'); $BM->mark('loading_time:_base_classes_end'); $BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_start'); $BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_end');
控制器执行耗费的时间:
echo $BM->elapsed_time('total_execution_time_start', 'controller_execution_time_( '.$class.' / '.$method.' )_end');