關於php Timer 頁面運行時間監測類別的相關介紹

jacklove
發布: 2023-03-31 09:32:01
原創
1471 人瀏覽過

php Timer 頁面運行時間監測類,可依不同key監控不同的運行時間

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 = &#39;Timer&#39;;
    private $_prefix = &#39;Timer_&#39;;
    /** 记录开始时间
    * @param String $key 标记
    */
    public function start($key=&#39;&#39;){
        $flag = $this->getKey($key);
        $this->_start[$flag] = $this->getMicrotime();
    }
    /** 记录结束时间
    * @param String $key 标记
    */
    public function end($key=&#39;&#39;){
        $flag = $this->getKey($key);
        $this->_end[$flag] = $this->getMicrotime();
    }
    /** 计算运行时间
    * @param  String $key 标记
    * @return float
    */
    public function getTime($key=&#39;&#39;){
        $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=&#39;&#39;){
        printf("%srun time %f ms\r\n", $key==&#39;&#39;? $key : $key.&#39; &#39;, $this->getTime($key)*1000);
    }
    /** 获取key
    * @param  String $key 标记
    * @return String 
    */
    private function getKey($key=&#39;&#39;){
        if($key==&#39;&#39;){
            return $this->_default_key;
        }else{
            return $this->_prefix.$key;
        }
    }
    /** 获取microtime
    */
    private function getMicrotime(){
        list($usec, $sec) = explode(&#39; &#39;, microtime());
        return (float)$usec + (float)$sec;
    }
} // class end
?>
登入後複製

demo:

#
<?php
require &#39;Timer.class.php&#39;;
$timer = new Timer();
$timer->start();
$timer->start(&#39;program1&#39;);
usleep(mt_rand(100000,500000));
$timer->end(&#39;program1&#39;);
$timer->printTime(&#39;program1&#39;);
$timer->start(&#39;program2&#39;);
usleep(mt_rand(100000,500000));
$timer->end(&#39;program2&#39;);
$timer->printTime(&#39;program2&#39;);
$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中文網。

相關推薦:

關於php 建構子支援不同個數參數的方法介紹

如何使用PDO查詢mysql避免SQL注入的方法

關於php 雙向佇列類別的講解

以上是關於php Timer 頁面運行時間監測類別的相關介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!