Measuring how long an operation takes is a common requirement in software development. Developers need to track database query execution, API response times, background jobs, file processing, and other application operations. Accurate timing helps identify performance problems and understand how an application behaves under different workloads.
PHP already provides functions such as microtime() and hrtime() for measuring execution time. However, working with raw numbers can make code difficult to read and maintain. Developers must remember whether a value represents seconds, milliseconds, microseconds, or nanoseconds.
PHP 8.6 introduces the new Time\Duration class to make working with elapsed time more structured. It represents a fixed period of time with nanosecond precision and provides methods for creating, comparing, adding, subtracting, and multiplying durations.
One important distinction is that Duration represents an amount of elapsed time; it does not automatically measure an operation. Developers can combine it with hrtime() to measure execution time and then store the result as a Duration object.
In this article, we will explore the Duration class in PHP 8.6, understand its methods, and implement practical examples for measuring application performance.
What Is the Duration Class in PHP 8.6?
The Time\Duration class is a built-in PHP class introduced in PHP 8.6. It represents a fixed amount of elapsed time, such as a timeout, delay, or measured execution period.
Unlike traditional timing approaches that use integers or floating-point values, Duration provides a dedicated object for representing time.
For example, consider the following code:
<?php
use Time\Duration;
$timeout = Duration::fromSeconds(5);
var_dump($timeout);
The code creates a Duration object representing five seconds.
The class supports nanosecond precision, which means it can represent very small time intervals.
A Duration object contains three important properties:
Property | Description |
|---|
seconds | Number of complete seconds |
nanoseconds | Fractional part of a second in nanoseconds |
negative | Indicates whether the duration is negative |
For example, a duration of 1.5 seconds is represented as:
<?php
use Time\Duration;
$duration = Duration::fromMilliseconds(1500);
echo $duration->seconds . PHP_EOL;
echo $duration->nanoseconds . PHP_EOL;
echo $duration->negative ? "Negative" : "Positive";
Output:
1
500000000
Positive
The seconds property contains the complete seconds, while nanoseconds contains the remaining fractional part.
This representation avoids relying on floating-point values to store fractional time.
Why PHP Introduced the Duration Class
Before PHP 8.6, developers generally represented elapsed time using integers or floating-point numbers.
For example:
<?php
$start = microtime(true);
// Application operation
usleep(500000);
$end = microtime(true);
$elapsed = $end - $start;
echo "Execution time: " . $elapsed . " seconds";
This approach works, but it has some limitations.
First, the developer must remember the unit associated with every value. A variable containing 500000 might represent microseconds, while another value containing 500 might represent milliseconds.
Second, performing calculations with raw time values can make code harder to understand.
For example:
<?php
$baseDelay = 100000;
$maximumDelay = 30000000;
$delay = min(
$baseDelay * 2,
$maximumDelay
);
Without comments, it is not immediately clear what these numbers represent.
PHP 8.6 provides Duration to address this problem.
<?php
use Time\Duration;
$baseDelay = Duration::fromMilliseconds(100);
$maximumDelay = Duration::fromSeconds(30);
$delay = $baseDelay->multiplyBy(2);
$delay = min($delay, $maximumDelay);
The code now communicates the intended time units directly.
The Duration class also supports comparison and arithmetic through dedicated methods.
Understanding the Duration Class Methods
The Duration class provides factory methods for creating time values and instance methods for performing calculations.
Creating Durations
PHP 8.6 provides several static factory methods.
Method | Purpose | Example |
|---|
fromNanoseconds() | Creates a duration from nanoseconds | Duration::fromNanoseconds(500000) |
fromMicroseconds() | Creates a duration from microseconds | Duration::fromMicroseconds(500) |
fromMilliseconds() | Creates a duration from milliseconds | Duration::fromMilliseconds(250) |
fromSeconds() | Creates a duration from seconds | Duration::fromSeconds(10) |
fromMinutes() | Creates a duration from minutes | Duration::fromMinutes(5) |
fromHours() | Creates a duration from hours | Duration::fromHours(2) |
fromIso8601DurationString() | Creates a duration from an ISO 8601 duration string | Duration::fromIso8601DurationString("PT5M") |
These methods make it easier to create durations without manually converting between time units.
Example:
<?php
use Time\Duration;
$milliseconds = Duration::fromMilliseconds(500);
$seconds = Duration::fromSeconds(5);
$minutes = Duration::fromMinutes(2);
$hours = Duration::fromHours(1);
echo $milliseconds->nanoseconds . PHP_EOL;
echo $seconds->seconds . PHP_EOL;
echo $minutes->seconds . PHP_EOL;
echo $hours->seconds . PHP_EOL;
The factory methods accept non-negative integer values. Negative durations can be created through operations such as sub() and negate().
Adding Durations
The add() method combines two Duration objects.
<?php
use Time\Duration;
$databaseTime = Duration::fromMilliseconds(250);
$apiTime = Duration::fromMilliseconds(500);
$totalTime = $databaseTime->add($apiTime);
echo $totalTime->seconds . PHP_EOL;
echo $totalTime->nanoseconds . PHP_EOL;
The resulting duration represents 750 milliseconds.
This is useful when measuring different stages of an application and calculating their combined execution time.
Subtracting Durations
The sub() method subtracts one duration from another.
<?php
use Time\Duration;
$first = Duration::fromSeconds(10);
$second = Duration::fromSeconds(4);
$result = $first->sub($second);
echo $result->seconds;
Output:
6
The result is a new Duration object.
If the second duration is greater than the first, the result becomes negative.
Multiplying Durations
The multiplyBy() method multiplies a duration by an integer.
<?php
use Time\Duration;
$delay = Duration::fromMilliseconds(500);
$repeatedDelay = $delay->multiplyBy(4);
echo $repeatedDelay->seconds . PHP_EOL;
echo $repeatedDelay->nanoseconds . PHP_EOL;
The result represents two seconds.
This method is useful when calculating retry delays, repeated operations, and timeout values.
Dividing Durations
The divideBy() method divides a duration by an integer.
<?php
use Time\Duration;
$totalTime = Duration::fromSeconds(10);
$averageTime = $totalTime->divideBy(4);
echo $averageTime->seconds . PHP_EOL;
echo $averageTime->nanoseconds . PHP_EOL;
The resulting duration represents 2.5 seconds.
When division produces a fractional nanosecond, the result is truncated to the supported nanosecond precision.
The divisor must be non-zero.
Comparing Durations
PHP 8.6 supports comparison operators for Duration objects.
<?php
use Time\Duration;
$shortTimeout = Duration::fromSeconds(5);
$longTimeout = Duration::fromSeconds(10);
if ($shortTimeout < $longTimeout) {
echo "The first timeout is shorter.";
}
Developers can also use the compare() method.
<?php
use Time\Duration;
$first = Duration::fromSeconds(5);
$second = Duration::fromSeconds(10);
$result = Duration::compare($first, $second);
echo $result;
The method returns:
-1 when the first duration is smaller.
0 when both durations are equal.
1 when the first duration is greater.
This method is particularly useful when sorting collections of durations.
Measuring Execution Time With hrtime() and Duration
The Duration class provides a structured representation of elapsed time, but developers still need a clock source to measure an operation.
PHP provides hrtime(), a high-resolution monotonic clock function.
Unlike wall-clock time, a monotonic clock is designed to measure elapsed time without being affected by changes to the system clock.
When hrtime(true) is used, it returns an integer representing nanoseconds.
We can combine this function with Duration::fromNanoseconds().
Consider the following example:
<?php
use Time\Duration;
$start = hrtime(true);
// Simulate an application operation
usleep(500000);
$end = hrtime(true);
$elapsedNanoseconds = $end - $start;
$duration = Duration::fromNanoseconds(
$elapsedNanoseconds
);
echo "Execution time: ";
echo $duration->seconds . " seconds and ";
echo $duration->nanoseconds . " nanoseconds";
Here is what happens:
hrtime(true) records the starting timestamp.
The application performs an operation.
hrtime(true) records the ending timestamp.
The difference between the two values gives the elapsed time in nanoseconds.
Duration::fromNanoseconds() converts the result into a Duration object.
This approach provides a clear separation between measuring time and representing time.
It is also useful when building reusable performance-monitoring utilities.
Creating a Reusable Execution Time Measurement Function
In real applications, developers may need to measure execution time across multiple operations.
Instead of repeating the same timing logic, we can create a reusable function.
<?php
use Time\Duration;
function measureExecutionTime(callable $operation): Duration
{
$start = hrtime(true);
$operation();
$end = hrtime(true);
return Duration::fromNanoseconds(
$end - $start
);
}
$duration = measureExecutionTime(function () {
// Simulate database processing
usleep(300000);
});
echo "Execution time: ";
echo $duration->seconds . ".";
echo $duration->nanoseconds;
The function accepts any callable operation and returns a Duration object.
This makes it possible to measure different operations without duplicating the timing code.
However, this basic implementation measures only successfully completed operations. If the operation throws an exception, the exception propagates to the caller and no duration is returned.
If an application needs to record execution time even when an operation fails, a try/finally block can be used.
<?php
use Time\Duration;
function measureExecutionTime(callable $operation): Duration
{
$start = hrtime(true);
try {
$operation();
} finally {
$end = hrtime(true);
$duration = Duration::fromNanoseconds(
$end - $start
);
error_log(
"Operation duration: " .
$duration->seconds . "." .
$duration->nanoseconds
);
}
}
The finally block executes whether the operation completes successfully or throws an exception.
The exception is still propagated to the caller.
For production applications, the measured duration can be sent to an application logging or monitoring system.
Using Duration for API Request Timeouts
Timeouts are important when applications communicate with external APIs.
An application should not wait indefinitely for a remote service to respond.
The Duration class provides a convenient way to represent timeout values.
For example:
<?php
use Time\Duration;
$connectionTimeout = Duration::fromSeconds(5);
$requestTimeout = Duration::fromSeconds(15);
if ($connectionTimeout < $requestTimeout) {
echo "Connection timeout is shorter than request timeout.";
}
The example compares two timeout configurations.
The Duration object itself does not enforce a timeout. The HTTP client or networking library must support the timeout value or convert it into the unit required by its configuration.
This distinction is important when integrating Duration into existing applications.
For example, if an HTTP library expects milliseconds, developers can use the seconds and nanoseconds properties to perform an appropriate conversion.
Using Duration for Exponential Backoff
Exponential backoff is a common technique used when retrying failed operations.
Instead of retrying immediately, an application increases the waiting time between attempts.
This is useful when communicating with external APIs, message brokers, and distributed services.
Consider the following implementation:
<?php
use Time\Duration;
function calculateRetryDelay(
Duration $baseDelay,
Duration $step,
int $attempt
): Duration {
$delay = $baseDelay->add(
$step->multiplyBy(2 ** $attempt)
);
$maximumDelay = Duration::fromSeconds(30);
return min($delay, $maximumDelay);
}
$baseDelay = Duration::fromSeconds(1);
$step = Duration::fromMilliseconds(100);
$attempt = 3;
$delay = calculateRetryDelay(
$baseDelay,
$step,
$attempt
);
echo $delay->seconds . ".";
echo $delay->nanoseconds;
The calculation uses a one-second base delay and increases the additional delay according to the retry attempt.
The maximum delay is limited to 30 seconds.
Because Duration objects support comparison, PHP's min() function can compare the two values directly.
In production systems, retry policies should also consider maximum retry counts, request deadlines, jitter, and the type of failure being handled.
Using Duration With the PHP 8.6 Polling API
Another important use case is the new PHP 8.6 I/O Polling API.
The Io\Poll\Context class uses Duration to represent how long the application should wait for events.
For example:
<?php
use Io\Poll\Context;
use Time\Duration;
$poll = new Context();
$timeout = Duration::fromSeconds(5);
$events = $poll->wait($timeout);
if (count($events) === 0) {
echo "No events received within the timeout.";
} else {
echo "Polling events received: ";
echo count($events);
}
The wait() method waits for polling events for up to five seconds.
Developers can also use a zero-duration timeout to perform a non-blocking poll.
<?php
use Io\Poll\Context;
use Time\Duration;
$poll = new Context();
$events = $poll->wait(
Duration::fromNanoseconds(0)
);
This allows the application to check for immediately available events without waiting.
The Duration class makes timeout configuration easier to understand and integrates naturally with the Polling API.
Duration Class vs. DateInterval vs. hrtime()
PHP developers may encounter several time-related APIs. Although they are related, they serve different purposes.
Feature | Duration | DateInterval | hrtime() |
|---|
Main purpose | Represent fixed elapsed time | Represent date and calendar intervals | Measure high-resolution timestamps |
Nanosecond precision | Yes | No | Yes |
Immutable | Yes | No | Returns an array or integer |
Calendar operations | No | Yes | No |
Arithmetic | Dedicated methods | Date and interval operations | Manual calculations |
Typical use | Timeouts and elapsed durations | Calendar calculations | Performance measurement |
PHP version | PHP 8.6 | Available in earlier PHP versions | Available in earlier PHP versions |
Use Duration when representing a fixed amount of elapsed time.
Use DateInterval when working with calendar-based operations, such as moving a date forward by one month.
Use hrtime() when measuring execution time.
These APIs complement one another and should not be treated as direct replacements.
Advantages of the Duration Class
The new Duration class provides several practical benefits.
Clear Time Representation
Developers can create durations using meaningful methods such as fromSeconds(), fromMilliseconds(), and fromMinutes().
This reduces confusion about time units.
Nanosecond Precision
Duration can represent fractional seconds with nanosecond precision.
This is useful for performance monitoring and applications that need accurate elapsed-time representation.
Immutable Objects
Duration objects are immutable. Operations such as add(), sub(), and multiplyBy() return new objects instead of modifying existing values.
This makes calculations easier to reason about.
Built-In Comparison
Developers can compare Duration objects using standard comparison operators.
There is no need to manually convert every duration into milliseconds or seconds before comparing values.
Useful for Timeout Management
The class integrates with the PHP 8.6 Polling API and provides a consistent way to represent timeouts.
Better Readability
A value created using Duration::fromMilliseconds(500) communicates its meaning more clearly than an unexplained integer such as 500.
Disadvantages and Limitations
Although Duration improves time handling, developers should understand its limitations.
Requires PHP 8.6 or Later
The native Time\Duration class is available in PHP 8.6 and later.
Applications running earlier PHP versions cannot use it without a compatible alternative.
Does Not Measure Time Automatically
Duration represents elapsed time but does not provide a built-in stopwatch that starts and stops automatically.
Developers still need a clock source such as hrtime() to measure an operation.
Does Not Support Calendar Units
Duration does not represent calendar months or years.
A calendar month has a different length depending on the month, so DateInterval remains appropriate for calendar-based calculations.
Arithmetic Uses Methods
Developers must use methods such as add(), sub(), multiplyBy(), and divideBy() rather than applying ordinary arithmetic operators directly to Duration objects.
Range Limitations
The maximum representable duration depends on the platform's integer size.
Operations that exceed the supported range throw a Time\TimeException.
Best Practices for Using Duration in Production
The following practices can help developers use the Duration class effectively.
Use hrtime() for performance measurement. A monotonic clock is more appropriate than wall-clock time when calculating elapsed execution time.
Keep time units explicit. Use factory methods such as fromMilliseconds() and fromSeconds() instead of unexplained numeric values.
Reuse Duration objects for timeout configuration. Centralize timeout values so they can be maintained consistently across application components.
Prefer immutable calculations. Store the result of add(), sub(), or multiplyBy() in a new variable instead of expecting the original object to change.
Use DateInterval for calendar calculations. Do not use Duration when calculating calendar months, years, or timezone-sensitive date changes.
Handle exceptions. Operations that exceed the supported range can throw Time\TimeException. Invalid ISO 8601 duration strings should also be handled appropriately.
Avoid unnecessary precision conversions. Keep values in nanoseconds when working with high-resolution timing and convert them only when required by another system.
Separate measurement from business logic. Use reusable timing utilities instead of adding measurement code throughout every application method.
Use realistic performance tests. A single measurement is not sufficient to understand application performance. Repeat tests under representative workloads and compare the results.
Avoid logging every operation unnecessarily. Excessive performance logging can generate large amounts of data and add overhead to an application.
Common Mistakes Developers Should Avoid
Using microtime() for Monotonic Timing
microtime() returns wall-clock time information.
For measuring elapsed execution time, hrtime() is generally the better choice because it uses a monotonic clock.
Confusing Duration With DateInterval
Duration represents a fixed amount of elapsed time, while DateInterval supports calendar-based date calculations.
Choosing the wrong class can introduce unexpected behavior when working with months, days, and daylight-saving transitions.
Assuming Duration Automatically Enforces Timeouts
Creating a Duration object does not automatically stop a database query or HTTP request.
The application must pass the value to a component that supports timeout handling.
Performing Direct Arithmetic on Duration Objects
The Duration class provides dedicated arithmetic methods.
Use the following approach:
<?php
use Time\Duration;
$first = Duration::fromSeconds(5);
$second = Duration::fromSeconds(3);
$total = $first->add($second);
Do not assume that ordinary addition or multiplication operators are supported.
Ignoring Negative Durations
Subtracting a larger duration from a smaller one can produce a negative result.
Applications should check the sign when negative values are not valid for a particular business operation.
Troubleshooting Duration Class Issues
Problem | Possible Cause | Recommended Solution |
|---|
Class Time\Duration not found | PHP version is older than 8.6 | Upgrade PHP or use an alternative implementation |
Unexpected time value | Incorrect unit conversion | Verify whether the input represents seconds, milliseconds, or nanoseconds |
Negative duration | Larger duration was subtracted from a smaller one | Check the comparison before subtraction |
TimeException occurs | Duration exceeds the supported range | Validate values before performing calculations |
Invalid ISO 8601 duration | Incorrect duration string | Validate the input format |
Arithmetic operation fails | Unsupported operators were used | Use add(), sub(), multiplyBy(), or divideBy() |
Execution time is inconsistent | Wall-clock timing or environmental variation | Use hrtime() and repeat measurements |
Conclusion
The Time\Duration class in PHP 8.6 provides a structured way to represent fixed amounts of elapsed time. It introduces nanosecond precision, immutable objects, factory methods, arithmetic operations, and built-in comparison support.
When combined with hrtime(), it becomes useful for measuring application execution time, tracking database operations, monitoring API performance, and creating reusable performance measurement utilities.
It also provides a natural way to represent timeout values in the PHP 8.6 Polling API and other components that work with elapsed time.
For developers building modern PHP applications, understanding the difference between Duration, DateInterval, and hrtime() is important. Each serves a different purpose, and choosing the correct one helps make time-related code more readable, predictable, and maintainable.
Join the conversation! Your thoughts help the community grow.