Friday, October 17, 2025
HomeLanguagesHow to measure the speed of code written in PHP?

How to measure the speed of code written in PHP?

Use timestamp function to measure the speed of code. The timestamp function placed twice in a program one at starting of program and another at end of the program. Then the time difference between end time and start time is the actual speed of code. PHP uses microtime($get_as_float) function to measure the speed of code.

microtime($get_as_float): The microtime() function is an inbuilt function in PHP which is used to return the current Unix timestamp with microseconds. The $get_as_float is sent as a parameter to the microtime() function and it returns the string microsec sec by default.

Syntax:

microtime( $get_as_float )

Parameters: This function accepts single parameter $get_as_float which is optional. If $get_as_float is set to TRUE then it specify that the function should return a float, instead of a string.

Return Type: It returns the string microsec sec by default, where sec is the number of seconds since the Unix Epoch (0:00:00 January 1, 1970, GMT), and microsec is the microseconds part. If the $get_as_float parameter is set to TRUE, it returns a float representing the current time in seconds since the Unix epoch accurate to the nearest microsecond.

Example 1: This example use microtime() function to measure speed of code.




<?php
  
// Use microtime() function to measure
// starting time
$time_start = microtime(true);
  
// Code of program
$num = 0;
  
for( $i = 0; $i < 100000000; $i += 1 ) {
    $num += 10;
}
  
// Use microtime() function to measure
// ending time
$time_end = microtime(true);
  
// Time difference
$time = $time_end - $time_start;
  
echo $time;
  
?>


Output:

4.1413249969482

Example 2: This method uses time() function which returns time in seconds, not much accurate execution time can be measured.




<?php
  
// Use time() function to measure
// starting time
$time_start = time();
  
// Code of program
$num = 0;
for( $i = 0; $i < 100000000; $i += 1) {
    $num += 10;
}
  
  
// Use time() function to measure
// ending time
$time_end = time();
  
// Time difference
$time = $time_end - $time_start;
  
echo $time;
  
?>


Output:

4
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS