首页  >  文章  >  后端开发  >  php Timer 页面运行时间监测类

php Timer 页面运行时间监测类

黄舟
黄舟原创
2017-02-17 10:14:261121浏览

php Timer 页面运行时间监测类,可按不同key监测不同的运行时间


Timer.class.php


getKey($key);
        $this->_start[$flag] = $this->getMicrotime();
    }


    /** 记录结束时间
    * @param String $key 标记
    */
    public function end($key=''){
        $flag = $this->getKey($key);
        $this->_end[$flag] = $this->getMicrotime();
    }


    /** 计算运行时间
    * @param  String $key 标记
    * @return float
    */
    public function getTime($key=''){
        $flag = $this->getKey($key);
        if(isset($this->_end[$flag]) && isset($this->_start[$flag])){
            return (float)($this->_end[$flag] - $this->_start[$flag]);
        }else{
            return 0;
        }
    }


    /** 输出页面运行时间
    * @param  String $key 标记
    * @return String
    */
    public function printTime($key=''){
        printf("%srun time %f ms\r\n", $key==''? $key : $key.' ', $this->getTime($key)*1000);
    }


    /** 获取key
    * @param  String $key 标记
    * @return String 
    */
    private function getKey($key=''){
        if($key==''){
            return $this->_default_key;
        }else{
            return $this->_prefix.$key;
        }
    }


    /** 获取microtime
    */
    private function getMicrotime(){
        list($usec, $sec) = explode(' ', microtime());
        return (float)$usec + (float)$sec;
    }


} // class end

?>

demo:



start();

$timer->start('program1');
usleep(mt_rand(100000,500000));
$timer->end('program1');
$timer->printTime('program1');

$timer->start('program2');
usleep(mt_rand(100000,500000));
$timer->end('program2');
$timer->printTime('program2');

$timer->end();
$timer->printTime();

?>

demo运行输出:


program1 run time 163.285971 ms
program2 run time 100.347042 ms
run time 264.035940 ms



 以上就是php Timer 页面运行时间监测类的内容,更多相关内容请关注PHP中文网(www.php.cn)!


声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn