php實現的timer頁面運行時間監(jiān)測類

字號:


    本文實例講述了php實現的timer頁面運行時間監(jiān)測類及其用法,是一款非常實用的php類文件。分享給大家供大家參考。具體分析如下:
    該php timer頁面運行時間監(jiān)測類,可按不同key監(jiān)測不同的運行時間。
    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 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示例代碼如下:
    <?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
    希望本文所述對大家的php程序設計有所幫助。