Start and stop a timer PHP
I need some information regarding starting and stopping a timer in PHP. I need to measure the elapsed time from the start of my .exe program (I'm using exec()
function in my php script) until it completes the execution and display the time it took in seconds.
How can I do this?
Solution 1:
You can use microtime
and calculate the difference:
$time_pre = microtime(true);
exec(...);
$time_post = microtime(true);
$exec_time = $time_post - $time_pre;
Here's the PHP docs for microtime
: http://php.net/manual/en/function.microtime.php
Solution 2:
Since PHP 7.3 the hrtime function should be used for instrumentation.
$start = hrtime(true);
// run your code...
$end = hrtime(true);
echo ($end - $start); // Nanoseconds
echo ($end - $start) / 1000000; // Milliseconds
echo ($end - $start) / 1000000000; // Seconds
The mentioned microtime function relies on the system clock. Which can be modified e.g. by the ntpd program on ubuntu or just the sysadmin.
Solution 3:
Use the microtime
function. The documentation includes example code.
Solution 4:
For your purpose, this simple class should be all you need:
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
Solution 5:
You can use 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;
}
}
?>