php代码时间消耗统计类

发布时间:2019-08-08 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php代码时间消耗统计类脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
这段时间在做项目的后端服务优化,数据量比较大的两个后台服务一个是首页微博列表获取,一个是个人动态的获取,先从性能来分析,需要用到时间统计,所以抽时间写了一个函数的时间消耗统计类,实现上比较简单,但是还算好用,分享给大家,如果有错误或者可以改进的话欢迎指出。
我统计的结果,wifi环境下基本上拉取16条数据需要3~4s,这个数据还是相当高了,接下来找找方法看看能不能优化。

使用举例:
<?php
    require_once 'TimeHelper.class.php';
    $myTimeHelper = new TimeHelper();
    #代码段A
    $myTimeHelper->recordNow("代码A消耗");
    #代码段B
    $myTimeHelper->recordNow("代码B消耗");
    $myTimeHelper->printInfo();

?>


TimeHelper.class.php
<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2014 doBell www.dobell.me
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: congorz <congorz@yeah.net>
// +----------------------------------------------------------------------

/**
 * doSchool-服务器端 服务消耗时间统计API
 * @author    congorz <congorz@yeah.net>
 * @lastdate 2014年12月25日19:51:31
 */
class TimeHelper{

    private $startTime;
    private $tempTime;
    private $spendTime;
    private $recordString;

    public function __construct() {
        $this->startTime = microtime(true);
        $this->tempTime = array();
        $this->spendTime = array();
        $this->recordStrs = array();
        $this->tempTime[] = $this->startTime;
    }

    public function recordNow($str) {
        //str是对于前面代码功能的注释标签
        $this->recordStrs[] = $str;
        $this->tempTime[] = microtime(true);
    }

    public function handle() {
        $count = count($this->tempTime);
        $total = 0;
        for ($i=1; $i < $count; $i++) {
            $oneSpend = $this->tempTime[$i] - $this->tempTime[$i-1];
            $str_oneSpend = VAR_export($oneSpend, TRUE);  
            if(substr_count($str_oneSpend,"E")){
                //科学计数法的处理,暂时没做
            }
            $total += $oneSpend;
            $tempStr = $this->recordStrs[$i-1];
            $this->spendTime["$tempStr"] = $oneSpend;
        }
        $this->spendTime["总计时间"] = $total;
    }

    public function printInfo() {
        $this->handle();
        print_r($this->spendTime);
    }
}
?>

脚本宝典总结

以上是脚本宝典为你收集整理的php代码时间消耗统计类全部内容,希望文章能够帮你解决php代码时间消耗统计类所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。