Подтвердить что ты не робот

Запуск и остановка таймера PHP

Мне нужна информация о запуске и остановке таймера в PHP. Мне нужно измерить прошедшее время с момента запуска моей программы .exe(Im, используя функцию exec() в моем PHP скрипт), пока она не завершит выполнение и не отобразит время, затраченное секундами. Есть ли способ, как я могу это сделать.

Спасибо

4b9b3361

Ответ 1

Вы можете использовать microtime и рассчитать разницу:

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

Здесь PHP-документы для microtime: http://php.net/manual/en/function.microtime.php

Ответ 2

Используйте функцию microtime. Документация содержит пример кода.

Ответ 3

Для вашей цели этот простой класс должен быть всем, что вам нужно:

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

Ответ 4

Вы можете использовать Timer Class

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

?>