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()
class Timer
{
private $startTime = null;
public function __construct($showSeconds = true)
{
$this->startTime = microtime(true);
echo 'Working - please wait...' . PHP_EOL;
}
public function __destruct()
{
$endTime = microtime(true);
$time = $endTime - $this->startTime;
$hours = (int)($time / 60 / 60);
$minutes = (int)($time / 60) - $hours * 60;
$seconds = (int)$time - $hours * 60 * 60 - $minutes * 60;
$timeShow = ($hours == 0 ? "00" : $hours) . ":" . ($minutes == 0 ? "00" : ($minutes < 10 ? "0" . $minutes : $minutes)) . ":" . ($seconds == 0 ? "00" : ($seconds < 10 ? "0" . $seconds : $seconds));
echo 'Job finished in ' . $timeShow . PHP_EOL;
}
}
$t = new Timer(); // echoes "Working, please wait.."
[some operations]
unset($t); // echoes "Job finished in h:m:s"
Since PHP 7.3 the hrtime function should be used for any timing.
$start = hrtime(true);
// execute...
$end = hrtime(true);
echo ($end - $start); // Nanoseconds
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.