温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

利用php怎么对Timer页面的运行时间进行监测

发布时间:2020-12-24 15:12:19 来源:亿速云 阅读:175 作者:Leah 栏目:开发技术

利用php怎么对Timer页面的运行时间进行监测?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

Timer.class.php类文件如下:

<?php 
/** Timer class, 计算页面运行时间,可按不同key计算不同的运行时间 
*  Date:  2014-02-28 
*  Author: fdipzone 
*  Ver:  1.0 
* 
*  Func: 
*  public start    记录开始时间 
*  public end     记录结束时间 
*  public getTime   计算运行时间 
*  pulbic printTime  输出运行时间 
*  private getKey    获取key 
*  private getMicrotime 获取microtime 
*/ 
 
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 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示例代码如下:

<?php 
 
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运行输出:

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

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI