Friday, September 5, 2025
HomeLanguagesHow to Start and Stop a Timer in PHP ?

How to Start and Stop a Timer in PHP ?

You can start and stop a timer in PHP using the microtime() function in PHP. The microtime() function is an inbuilt function in PHP which is used to return the current Unix timestamp with microseconds.

 In this article, you will learn the uses of the microtime() function.

Syntax:

microtime( $get_as_float )
  • Parameters: The $get_as_float is sent as a parameter to the microtime() function, and it returns the string microsec by default.
  • Return Value: By default, the microtime() function returns the time as a string, but if it is set to TRUE, then the function returns the time as a string. So the default is FALSE.

Example 1: The following example uses false as the parameter for the microtime() method.

PHP




<?php
  
  // Displaying the micro time as a string
  echo ("Displaying the micro time as a string :");
  echo(microtime());
?>


Output

Displaying the micro time as a string :0.62248800 1620222618

Example 2: The following example uses true as the parameter for the microtime() method.

PHP




<?php
  
    // Displaying the micro time as a float type
    echo ("Displaying the micro time as a float :");
    echo(microtime(true));
?>


Output

Displaying the micro time as a float :1620222618.9294

The microtime() function can also be used to measure the speed of code written in PHP, which is discussed below.

Note: The microtime() function is an inbuilt function in PHP which is used to return the current Unix timestamp with microseconds. 

Example 3: In the following code, the timestamp function is placed twice in a program once at starting of the 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




<?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 += 5;
}
  
// Use microtime() function to measure
// ending time
$time_end = microtime(true);
  
// Time difference
$time = $time_end - $time_start;
  
echo "The speed of code = ".$time;
  
?>


Output

The speed of code = 3.625461101532

Example 4: The following code uses the microtime() function to get the current time in milliseconds.

PHP




<?php
   //current time in milliseconds
    $milliseconds = round(microtime(true) * 1000);
    echo $milliseconds;
?>


Output

1620222618825
RELATED ARTICLES

Most Popular

Dominic
32265 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6634 POSTS0 COMMENTS
Nicole Veronica
11801 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11864 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6703 POSTS0 COMMENTS
Umr Jansen
6718 POSTS0 COMMENTS