2011-11-29 482 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