Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to measure the execution time of code

Short answer

Remember the timer reading before and after the code:

<?php
 
$start = hrtime(true);
 
$sum = 0;
 
for ($i = 0; $i < 1_000_000; $i++) {
    $sum += $i;
}
 
echo round((hrtime(true) - $start) / 1e6, 2), ' ms';

A function for measuring

Wrap the measurement in a function that takes the code:

<?php
 
function measure(callable $code): float
{
    $start = hrtime(true);
    $code();
 
    return (hrtime(true) - $start) / 1e6;
}
 
$ms = measure(fn () => array_sum(range(1, 100000)));
 
echo $ms < 1000 ? 'fast enough' : 'too slow';

Output:

fast enough

One measurement means nothing

The time depends on how busy the computer is. Repeat the code many times and compare the total — and only on the same machine.

Functions used in this recipe

  • hrtime — Returns a high-resolution timer reading in nanoseconds.
  • microtime — Returns the current time with microsecond precision.
  • memory_get_usage — Returns the amount of memory the program uses.

Thanks for reading!

Donate to the site — we work hard for you.