加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php实现的Timer页面运行时间监测类

发布时间:2020-12-12 20:24:12 所属栏目:PHP教程 来源:网络整理
导读:本篇章节讲解php实现的Timer页面运行时间监测类及其用法,是一款非常实用的PHP类文件。供大家参考研究。具体分析如下: 该php Timer页面运行时间监测类,可按不同key监测不同的运行时间。 Timer.class.php类文件如下: class Timer{ // class start

本篇章节讲解php实现的Timer页面运行时间监测类及其用法,是一款非常实用的PHP类文件。分享给大家供大家参考。具体分析如下:

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

Timer.class.php类文件如下:

class Timer{ // class start

private $_start = array();
private $_end = array();
private $_default_key = 'Timer';
private $prefix = 'Timer';

/** 记录开始时间

  • @param String $key 标记
    */
    public function start($key=''){
    $flag = $this->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 msrn",$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示例代码如下:

require 'Timer.class.php';

$timer = new Timer();
$timer->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运行输出:

完整实例源码点击此处。

希望本文所述对大家的PHP程序设计有所帮助。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读