php實現的Timer頁面已耗用時間監測類

來源:互聯網
上載者:User

   本文執行個體講述了php實現的Timer頁面已耗用時間監測類及其用法,是一款非常實用的PHP類檔案。分享給大家供大家參考。具體分析如下:

  該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 = '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程式設計有所協助。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.