Skip to content
Related Articles

Related Articles

Improve Article

How to Start and Stop a Timer in PHP ?

  • Last Updated : 10 May, 2021

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



My Personal Notes arrow_drop_up
Recommended Articles
Page :