2011-11-29 522 views
29

我需要一些關於在PHP中啓動和停止計時器的信息。我需要從啓動我的.exe程序(我的php腳本中使用exec()函數)開始測量已用時間,直到它完成執行並顯示花在秒內的時間。 有什麼辦法可以做到這一點。啓動和停止計時器PHP

感謝

回答

3

您可以使用Timer類

<?php 

class Timer { 

    var $classname = "Timer"; 
    var $start  = 0; 
    var $stop  = 0; 
    var $elapsed = 0; 

    # Constructor 
    function Timer($start = true) { 
     if ($start) 
     $this->start(); 
    } 

    # Start counting time 
    function start() { 
     $this->start = $this->_gettime(); 
    } 

    # Stop counting time 
    function stop() { 
     $this->stop = $this->_gettime(); 
     $this->elapsed = $this->_compute(); 
    } 

    # Get Elapsed Time 
    function elapsed() { 
     if (!$elapsed) 
     $this->stop(); 

     return $this->elapsed; 
    } 

    # Resets Timer so it can be used again 
    function reset() { 
     $this->start = 0; 
     $this->stop = 0; 
     $this->elapsed = 0; 
    } 

    #### PRIVATE METHODS #### 

    # Get Current Time 
    function _gettime() { 
     $mtime = microtime(); 
     $mtime = explode(" ", $mtime); 
     return $mtime[1] + $mtime[0]; 
    } 

    # Compute elapsed time 
    function _compute() { 
     return $this->stop - $this->start; 
    } 
} 

?> 
5

你的目的,這個簡單班級應該是你需要的全部:

class Timer { 
    private $time = null; 
    public function __construct() { 
     $this->time = time(); 
     echo 'Working - please wait..<br/>'; 
    } 

    public function __destruct() { 
     echo '<br/>Job finished in '.(time()-$this->time).' seconds.'; 
    } 
} 


$t = new Timer(); // echoes "Working, please wait.." 

[some operations] 

unset($t); // echoes "Job finished in n seconds." n = seconds elapsed