php中計算頁面加載時間幾種方法總結
來源:程序員人生 發布時間:2014-03-28 21:03:53 閱讀次數:2704次
大家可通常用的microtime()獲取頁面開始和結束時的時間并相減的話,計算結果是頁面運行 所經歷的一段時間,但這并不一定是該頁面自身運行的時間
實例代碼如下:
- <?php
-
-
-
- function fn(){
- list($a,$b) = explode(' ',microtime());
- return $a+$b;
- }
-
- $start_time = fn();
-
- for($i=0;$i<10000000;$i++){
-
- }
-
- $end_time = fn();
-
- echo $end_time-$start_time;
-
- echo '<br />';
- $t = $end_time-$start_time;
- echo round($t,2);
- ?>
使用microtime()獲取頁面開始和結束時的時間并相減的話,計算結果是頁面運行
所經歷的一段時間,但這并不一定是該頁面自身運行的時間.因為可能存在多個PHP腳
本頁面共同執行的情況,所以我覺得那個方法是不準確的
下面從網上找到一個關于php中計算頁面程序運行時間的實例有需要的朋友可參考一下.
最近寫了一個程序運行的時間計算類,供大家參考:
實例代碼如下:
- class Timer {
- private $StartTime = 0;
- private $StopTime = 0;
- private $TimeSpent = 0;
- function start(){
- $this->StartTime = microtime();
- }
- function stop(){
- $this->StopTime = microtime();
- }
- function spent(){
- if ($this->TimeSpent) {
- return $this->TimeSpent;
- } else {
- list($StartMicro, $StartSecond) = explode(" ", $this->StartTime);
- list($StopMicro, $StopSecond) = explode(" ", $this->StopTime);
- $start = doubleval($StartMicro) + $StartSecond;
- $stop = doubleval($StopMicro) + $StopSecond;
- $this->TimeSpent = $stop - $start;
- return substr($this->TimeSpent,0,8)."秒";
- }
- }
- }
- $timer = new Timer();
- $timer->start();
-
- $timer->stop();
- echo "程序運行時間為:".$timer->spent();
再看簡化程序 計算頁面加載時間
實例代碼如下:
- <?php
- class runtime
- {
- var $StartTime = 0;
- var $StopTime = 0;
- function get_microtime()
- {
- list($usec, $sec) = explode(' ', microtime());
- return ((float)$usec (float)$sec);
- }
-
- function start()
- {
- $this->StartTime = $this->get_microtime();
- }
-
- function stop()
- {
- $this->StopTime = $this->get_microtime();
- }
-
- function spent()
- {
- return round(($this->StopTime - $this->StartTime) * 1000, 1);
- }
- }
-
- $runtime= new runtime;
- $runtime->start();
-
- $a = 0;
- for($i=0; $i<1000000; $i )
- {
- $a = $i;
- }
-
- $runtime->stop();
- echo "頁面執行時間: ".$runtime->spent()." 毫秒";
- ?>
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈