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 '0.1512';
}
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 '2.53MB';
}
}
測試基準類可以在 控制器, 視圖,或者 模型.中使用,用法如下:標記一個開始點
標記一個結束點
運行elapsed_time函數顯示結果
下面是一個代碼示例:
$this->benchmark->mark('code_start');
// Some code happens here
$this->benchmark->mark('code_end');
echo $this->benchmark->elapsed_time('code_start', 'code_end');
注意:單詞“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');
如果你想你的基準數據對評測有效,你的標記點必須設置成對,並且每個標記點必須用_start 和_end結束.每一對標記點的前部必須相同.例如:
$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');