Displaying Page Load Time

It is very simple to show page load times in PHP.

Method 1:
Place this at the very begin of your PHP code:

1
define('STARTING_MICROTIME', get_microtime());

Depending on how you like to organize your code have those functions some where, they are pretty straight forward:

1
2
3
4
5
6
7
8
9
function execution_time()
{
    return sprintf("%01.4f", get_microtime() - STARTING_MICROTIME);
}
function get_microtime()
{
    $time = explode(' ', microtime());
    return doubleval($time[0]) + $time[1];
}

And finally just use the execution_time() function to show the total time elapsed since the script started.

Method 2:
Place this at very beginning of your code.

1
define('PAGE_LOAD_START', microtime(true));

And this where you want to display the render time.

1
<?php echo round((microtime(true) - PAGE_LOAD_START), 4); ?>

This way is easier IMO. Using constants is not necessary, it just avoids problems in namespaces if your code is OOP like.

Leave a Reply