Measuring PHP page load time

When you want to measure the actual page load time of a PHP page most developers will get the microtime at the top of the page, whilst this does measure the page load time of the scripts running on the page it doesn't accurately measure the page load time of the script.

To do so you can use $_SERVER['REQUEST_TIME_FLOAT'] to get the actual start time of the page request. Which can differ by 0.01 second or so.

$total_time = ( ( explode(' ', microtime())[0] + explode(' ', microtime())[1] ) - $_SERVER['REQUEST_TIME_FLOAT'] );

If you're just looking for a timer function then this is the most accurate way to do so.

class Timer {
	private $start;
	
	public function __construct() {
		$this->start = ( explode(' ', microtime())[0] + explode(' ', microtime())[1] );
	}
	
	public function stop() {
		return ( explode(' ', microtime())[0] + explode(' ', microtime())[1] ) - $this->start;
	}
	
	public function reset() {
		$this::__construct();
	}
}

$timer = new Timer();
$total_time = $timer->stop();