Measure Page Load Time and Code Execution Time in PHP
How much time does your page or your code need to run? You can measure it with a few lines of PHP. This helps to find the slow parts of a script before your visitors do.
Measure the time of a piece of code
Take the time before and after the code with microtime(true). The difference is the time in seconds.
<?php
$start = microtime(true);
// The code that you want to measure
usleep(250000); // wait 0.25 second, as a test
$end = microtime(true);
echo "Execution time: " . round($end - $start, 2) . " seconds";
?>
Output:
Execution time: 0.25 seconds
Measure the full page load time
PHP already knows when the request started, in $_SERVER["REQUEST_TIME_FLOAT"]. Put this code at the end of your page.
<?php
// At the end of the page
$time = microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"];
echo "Page generated in " . round($time, 4) . " seconds";
?>
This is the time that PHP needed on the server. It does not include the time to download the page in the browser.
Memory usage
<?php
echo "Peak memory: " . round(memory_get_peak_usage() / 1024 / 1024, 2) . " MB";
?>
A reusable timer function
hrtime(true) is more exact than microtime and it does not change when the server clock changes. It returns nanoseconds. This function measures any function that you give.
<?php
function measure(callable $task): float
{
$start = hrtime(true);
$task();
return (hrtime(true) - $start) / 1e9; // seconds
}
$seconds = measure(function () {
$sum = 0;
for ($i = 0; $i < 1000000; $i++) {
$sum += $i;
}
});
echo "The loop took " . round($seconds, 4) . " seconds";
?>
Related: PHP Functions and PHP Date and Time.
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |