Start and Stop a Timer in PHP

This article will introduce a method to start and stop a timer in PHP.

Use the microtime() Function to Start and Stop a Timer in PHP

We can use the microtime() function to start and stop the timer in PHP. The microtime() function notes the time in microseconds when it’s called. We will calculate the time difference between the stop time and the start timer to get the execution time. The correct syntax to use this function is as follows.

microtime($getAsFloat);

The microtime() function has one parameter only. The detail of its parameter is as follows.

Variables Description
$getAsFloat Boolean. If set to TRUE, then the function returns the time as a string, not as a float.

This function returns the time in microseconds. The program below shows the ways by which we can use the microtime() function to start and stop a timer in PHP.

<?php
$time_pre = microtime(true);
echo("This line will be executed.\n");
$time_post = microtime(true);
$exec_time = $time_post - $time_pre;
echo("The execution time is:\n");
echo($exec_time);
?>

Output:

This line will be executed.
The execution time is:
2.6941299438477E-5