How to Track PHP Script Execution Time
Tracking the execution time of a PHP script is essential for
optimizing performance and identifying bottlenecks in your web
applications. This article provides a straightforward guide on how to
measure PHP execution time using built-in functions like
microtime() and hrtime(), as well as how to
format the results for debugging and analysis.
Method 1: Using
microtime()
The most common way to measure execution time in PHP is by using the
microtime() function. By passing true as the
argument, it returns the current Unix timestamp with microseconds as a
float.
Here is a simple example:
<?php
// Start the timer
$start_time = microtime(true);
// Place your code here (e.g., a loop or database query)
usleep(500000); // Delays execution for 0.5 seconds
// End the timer
$end_time = microtime(true);
// Calculate the difference
$execution_time = $end_time - $start_time;
echo "Execution time: " . round($execution_time, 4) . " seconds";
?>Method 2: Using
hrtime() (Recommended for PHP 7.3+)
For more precise measurements, PHP 7.3 introduced the
hrtime() (high-resolution time) function. Unlike
microtime(), hrtime() uses the system’s
monotonic clock, meaning it is not affected by system time adjustments
(like NTP syncing).
By passing true, hrtime() returns the time
in nanoseconds as an integer.
<?php
// Start the high-resolution timer
$start = hrtime(true);
// Code to measure
usleep(500000);
// End the high-resolution timer
$end = hrtime(true);
// Calculate time in nanoseconds
$nanoseconds = $end - $start;
// Convert to milliseconds or seconds
$milliseconds = $nanoseconds / 1e+6;
$seconds = $nanoseconds / 1e+9;
echo "Execution time: " . round($seconds, 4) . " seconds (" . round($milliseconds, 2) . " ms)";
?>Method 3: Using the
$_SERVER Global
If you want to measure the execution time from the very moment the
request hits the server to a specific point in your script, you can use
the $_SERVER['REQUEST_TIME_FLOAT'] superglobal. This
variable contains the timestamp of the start of the request with
microsecond precision.
<?php
// Code to measure
usleep(500000);
// Calculate time elapsed since the request started
$execution_time = microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'];
echo "Total request execution time: " . round($execution_time, 4) . " seconds";
?>Best Practices for Performance Profiling
When tracking execution times, keep the following best practices in mind:
- Average the results: Run your script multiple times and calculate the average execution time to account for server load fluctuations.
- Format for readability: Use
round()ornumber_format()to limit the number of decimal places when outputting results. - Use professional profilers for complex apps: For large-scale applications, manual timing can be tedious. Consider using dedicated APM tools or PHP extensions like Xdebug or Blackfire.io for detailed visual profiling.