W3docs

How to Measure Script Execution Time in PHP

In this snippet, we demonstrate the simplest way of measuring the execution time of a string in PHP. Read on and check out the examples.

The time that is required for executing a PHP script is known as script execution time.

It is recommended to use a timing function like microtime() to calculate it. If you record the time before and after the script execution, you can easily determine the execution time.

Let’s take a look at a script sample:

php script sample

<?php

for ($i = 1; $i <= 1000; $i++) {
  echo "Hello W3docs!";
}

?>

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

Getting the Clock Time with microtime()

The <kbd class="highlighted">microtime()</kbd> function is used for getting the clock time. First, it should be used before the script starts, then, at the end of it. Afterwards, the formula (End_time – Start_time) should be used.

When called with true, the <kbd class="highlighted">microtime()</kbd> function returns the current time in seconds. The execution time is not fixed; it depends on system load, I/O operations, and other factors.

To be more precise, let’s see an example:

php use microtime() to get the script execution time

<?php

// Starting clock time in seconds
$start_time = microtime(true);
$a = 1;

// Start loop
for ($i = 1; $i <= 10000000; $i++) {
    $a++;
}

// End clock time in seconds
$end_time = microtime(true);

// Calculating the script execution time
$execution_time = $end_time - $start_time;

echo " Execution time of script = " . $execution_time . " sec";

?>

php script execution time

Execution time of script = 1.4305651187897 sec

Describing the microtime() Function

The <kbd class="highlighted">microtime()</kbd> function returns the current time with microsecond precision. By default, it returns a string in the format 'msec sec'. Passing true as a parameter returns the current time as a float in seconds.