How to Measure Script Execution Time in PHP

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

It is recommended to use a clock for calculating it. If you know the time before the script execution and after it, you will manage to get the execution time easily.

Let’s take a look at a script sample:

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

Getting the Clock Time with microtime()

The microtime() 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.

With the help of the microtime() function, time is returned in seconds. The execution time is not fixed, it is decided by the processor.

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


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

// Start loop 
for ($i = 1; $i <= 1000; $i++) {

// 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";

The output of this example will display the execution time of the script:

  Execution time of script = 1.6927719116211E-5 sec

Describing the microtime() Function

The microtime() function of PHP is used for returning the current Unix timestamp. It returns a string in msec sec. form by default.

Passing a boolean value as a parameter of this method will return the current time in seconds.

Initially, this function was introduced in PHP 4. Now, it operates with all the latest versions.

Do you find this helpful?

Related articles