2011-11-29 21 views
29

Ho bisogno di alcune informazioni riguardanti l'avvio e l'arresto di un timer in PHP. Ho bisogno di misurare il tempo trascorso dall'inizio del mio programma .exe (Im usando la funzione exec() nel mio script php) finché non completa l'esecuzione e mostra il tempo impiegato in secondi. C'è un modo in cui posso farlo.Avvio e arresto di un timer PHP

Grazie

risposta

74

È possibile utilizzare microtime e calcolare la differenza:

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

Ecco la documentazione di PHP per microtime: http://php.net/manual/en/function.microtime.php

+0

grazie mille per le vostre risposte! È stato davvero utile – 125369

6

Utilizzare la funzione microtime. La documentazione include codice di esempio.

3

È possibile utilizzare Timer Classe

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

per il vostro scopo, questo semplice la classe dovrebbe essere tutto ciò di cui hai bisogno:

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 
Problemi correlati