2011-11-29 32 views
29

Tôi cần một số thông tin về việc bắt đầu và dừng hẹn giờ trong PHP. Tôi cần phải đo thời gian trôi qua kể từ khi bắt đầu chương trình .exe của tôi (Im sử dụng hàm exec() trong tập lệnh php của tôi) cho đến khi nó hoàn thành việc thực thi và hiển thị thời gian cần thiết trong vài giây. Có cách nào để tôi có thể làm điều này không.Bắt đầu và ngừng hẹn giờ PHP

Cảm ơn

Trả lời

74

Bạn có thể sử dụng microtime và tính toán sự khác biệt:

$time_pre = microtime(true); 
exec(...); 
$time_post = microtime(true); 
$exec_time = $time_post - $time_pre; 

Dưới đây là các tài liệu PHP cho microtime: http://php.net/manual/en/function.microtime.php

+0

cảm ơn rất nhiều câu trả lời của bạn! Nó thực sự hữu ích – 125369

6

Sử dụng chức năng microtime. Tài liệu bao gồm mã ví dụ.

3

Bạn có thể sử dụng Timer Lớp

<?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

Đối với mục đích của bạn, điều này đơn giản lớp học nên là tất cả những gì bạn cần:

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