Skip to content

Core\Time::monotonic

Reads a clock that only moves forward and returns a Duration. Use it to measure how long something takes: read it before and after, and subtract the first reading from the second.

The value alone has no meaning. It counts from a fixed starting point in the running program, not from a date. A later reading is never smaller than an earlier one, even when somebody changes the system clock. For the date and time of day, use Core\Time::now instead. A fixed time set by a test changes now, and it does not change monotonic.

The examples below measure a loop, check that readings never go back, and report every step of a job that took longer than a limit.

Return value

Returns Core\Time\Duration. A Duration since a fixed starting point. A later reading is never smaller than an earlier one.

Examples

Measure a loop

<?nvs
// Shows how to measure how long a piece of code takes.
// Read the clock before and after the work.
var $start = Core\Time::monotonic();
int $sum = 0;
int $i = 0;
while ($i < 100000) {
$sum = $sum + $i;
$i = $i + 1;
}
var $end = Core\Time::monotonic();
// `minus` gives the time between the two readings as a `Duration`.
// The result changes on every run, so this prints only a check: "under 5 seconds".
Core\Time\Duration $took = $end->minus($start);
echo $sum, "\n";
echo $took->toMilliseconds() < 5000 ? 'under 5 seconds' : 'slow', "\n";
Output
4999950000
under 5 seconds

Readings never go back

<?nvs
// Shows that a later reading of `Core\Time::monotonic` is never smaller than an earlier one.
// This loop reads the clock 10000 times and counts every reading that is
// smaller than the one before it. This prints 0.
var $last = Core\Time::monotonic();
int $backwards = 0;
int $i = 0;
while ($i < 10000) {
var $next = Core\Time::monotonic();
if ($next->compareTo($last) < 0) {
$backwards = $backwards + 1;
}
$last = $next;
$i = $i + 1;
}
echo $backwards, "\n";
Output
0

Report slow steps

<?nvs
// Shows how a job reports every step that took longer than a limit.
// Each step here only waits, to stand in for real work such as a database query.
array<Core\Time\Duration> $steps = ['load' => 1ms, 'convert' => 100ms, 'save' => 1ms];
Core\Time\Duration $limit = 50ms;
// This prints "slow step: convert" and nothing for the two fast steps.
foreach ($steps as string $name => Core\Time\Duration $work) {
var $began = Core\Time::monotonic();
Core\Time::sleep($work);
Core\Time\Duration $took = Core\Time::monotonic()->minus($began);
if ($took->compareTo($limit) > 0) {
echo 'slow step: ', $name, "\n";
}
}
Output
slow step: convert