Skip to content

Core\Time\Duration::microseconds

Creates a duration of a given number of microseconds. A microsecond is one millionth of a second.

Use it when the number of microseconds is known only while the program runs, for example when it comes from a measurement or a log file. When the number is fixed, write the duration directly in the code, such as 250us. A negative number gives a negative duration. The number can be up to 9,223,372,036,854,775 microseconds, which is about 292 years. A larger number throws a RuntimeError.

toString shows the duration in the largest units that fit. So 1500 microseconds prints as 1ms500us.

Parameters

  • $nintThe count of microseconds; negative for a duration that runs backwards.

Return value

Returns Core\Time\Duration. A Duration of $n × 1000 nanoseconds.

Errors

  • RuntimeError$n microseconds is longer than a Duration can hold — past ±2⁶³ nanoseconds.

Examples

From a computed number

<?nvs
// Shows how to create a duration from a number of microseconds that the program computes.
int $samples = 3;
Core\Time\Duration $read = Core\Time\Duration::microseconds($samples * 500);
// 1500 microseconds is 1 millisecond and 500 microseconds. This prints 1ms500us.
echo $read->toString(), "\n";
// `toMicroseconds` returns the number again. This prints 1500.
echo $read->toMicroseconds(), "\n";
// A negative number gives a negative duration. This prints -42us.
echo Core\Time\Duration::microseconds(-42)->toString(), "\n";
Output
1ms500us
1500
-42us

Too many microseconds

<?nvs
// Shows what happens when the number of microseconds is too large for a duration.
// 9223372036854775 is the largest number that fits. This prints it again.
echo Core\Time\Duration::microseconds(9223372036854775)->toMicroseconds(), "\n";
// One more microsecond does not fit, so `microseconds` throws a `RuntimeError`.
try {
Core\Time\Duration::microseconds(9223372036854776);
} catch (RuntimeError $e) {
echo $e->message, "\n";
}
Output
9223372036854775
Core\Time\Duration::microseconds(): this duration is longer than `Core\Time\Duration` can hold

Add up query times from a log

<?nvs
// Adds up the database query times of one request, from a log that records them in microseconds.
array<int> $queryMicros = [120, 3400, 85];
int $sum = 0;
foreach ($queryMicros as int $us) {
$sum = $sum + $us;
}
Core\Time\Duration $spent = Core\Time\Duration::microseconds($sum);
// The three queries took 3605 microseconds together. This prints 3ms605us.
echo 'queries took ', $spent->toString(), "\n";
// The budget for all queries is 5 milliseconds. This prints "within budget".
echo $spent->compareTo(5ms) <= 0 ? 'within budget' : 'too slow', "\n";
Output
queries took 3ms605us
within budget