CodeIgniter 核心代码阅读-监控文件Benchmark.php

来源:互联网 发布:数控编程视频教学视频 编辑:程序博客网 时间:2024/05/16 10:37

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}';}}
测试基准类可以在 控制器, 视图,或者 模型.中使用,用法如下:

标记一个开始点
标记一个结束点
运行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');




原创粉丝点击