PHP microtime vs time for Performance Tracking
Measuring execution speed is crucial for optimizing PHP applications,
and developers often choose between the microtime() and
time() functions. While both functions retrieve the current
system time, they differ significantly in precision, return formats, and
suitability for benchmarking. This article explains the key differences
between microtime() and time(), demonstrating
why microtime() is the necessary choice for accurate
performance tracking and how to implement it.
The Key Difference: Precision
The fundamental difference between time() and
microtime() is the level of precision they offer:
time()returns the current Unix timestamp as an integer, which measures time in seconds.microtime()returns the current Unix timestamp with microseconds (millionths of a second).
Because modern PHP scripts and database queries execute in a fraction
of a second, the one-second resolution of time() is too
coarse for performance tracking.
Why time() Fails for Performance Tracking
If you attempt to measure the execution time of a PHP function using
time(), the result will almost always be inaccurate.
$start = time();
// Run a fast database query or loop
$end = time();
$executionTime = $end - $start;In most cases, $executionTime will register as
0 because the code executed in less than a second. If the
execution happens to span across the boundary of a second (e.g.,
starting at 12:00:00.99 and ending at 12:00:01.01), time()
will report an execution time of 1 second, even though the
actual duration was only 0.02 seconds.
Why microtime() is the Correct Choice
To accurately benchmark PHP code, you need microsecond precision. By
default, microtime() returns a string in the format “msec
sec” (e.g., “0.012345 1600000000”).
To make calculations easy, you should pass true as the
first argument: microtime(true). This instructs PHP to
return the timestamp as a float, representing the total number of
seconds since the Unix epoch, inclusive of microseconds.
Here is the standard way to measure execution time using
microtime():
$start = microtime(true);
// Code block to measure
usleep(50000); // Simulating a 50-millisecond delay
$end = microtime(true);
$executionTime = $end - $start;
echo "Execution time: " . round($executionTime, 4) . " seconds";In this setup, if the code takes 50 milliseconds to execute,
microtime(true) will accurately calculate and display
0.05 seconds.
Summary of Differences
| Feature | time() |
microtime(true) |
|---|---|---|
| Precision | Seconds | Microseconds |
| Return Type | Integer | Float (when passed true) |
| Primary Use Case | Session expiration, date storage | Code benchmarking, performance tracking |
| Accuracy | Low (not suitable for speed tests) | High (perfect for speed tests) |