Calculate the execution time in PHP

The execution time of the PHP script is the time taken for the script to be executed. Whenever we run the PHP code on the server, it takes some time to execute.

It is possible to calculate the script execution time in PHP. Here I am going to show you a trick that can measure the execution time easily. So stay with this article and continue through it…

To measure the execution time, we are going to get the clock time before execution. After the main coding part, we will again get the clock time. After that, we will get the difference between these two clock times which will be the time take to execute the script.

In PHP, we can get the clock time using the microtime() function.

Now, it is time to see the PHP code that can calculate the time taken for the script to be run. Below is our PHP code:

<?php 
  
// Start the clock time in seconds 
$start_time = microtime(true); 
$val=1; 
  
// Start loop 
for($i = 1; $i <=99999; $i++) 
{ 
    $val++; 
}  
  
// End the clock time in seconds 
$end_time = microtime(true); 
  
// Calculate the script execution time 
$execution_time = ($end_time - $start_time); 
  
echo " It takes ".$execution_time." seconds to execute the script"; 
?>

In the above PHP code, we are using a for loop with the counter 99999. In that way, it will take some time to execute the code.

Also, read: Array to JSON conversion in PHP using json_encode

After that, we are calculating the difference between the start and end time and displaying it. If we run our code, we will be able to see the execution time for the PHP code.

Leave a Reply

Your email address will not be published.