php uses microtime(true) to calculate the execution time of php program code

How to calculate the execution time of a php program code?

As for the system time, many students may be familiar with the time() function of php, but unfortunately the time() function only returns the seconds since the Unix epoch (January 1, 1970 00:00:00 GMT) to the current time Number.
Yes, it is seconds. Our php program code execution may not take more than one second, so time() does not apply. php provides a more accurate time function microtime():

microtime — Returns the current Unix timestamp and microseconds.

格式: mixed microtime ([ bool $get_as_float ] )

The function returns a string in the format "msec sec", where sec is the number of seconds since the Unix epoch (0:00:00 January 1, 1970 GMT), and msec is the microsecond part.
If the input argument is true, microtime() will return a float.

For example: echo microtime(); will return: 0.08845800 1376983061.

echo microtime(true); returns: 1376983061.08845800

used microtime() in dedecms and Kangsheng's UCenter code then string delimited

Microtime(true) is used in the thinkphp3.2 framework code;

Well, then things are very simple, in order to avoid complex string conversion of the returned result, we set the microtime() input parameter to true, so that the returned result is a floating-point number.
Then it is calculated once at the beginning and end of the program, and the subtraction of the two results is the execution time of the program. (There is a sentence in the PHP manual: Never compare two floats for equality.)
Finally use number_format to format floats. This method is for testing purposes only, and results are not necessarily accurate.

code show as below:

[php]  view plain copy  
 
  1. <?php  
  2.   
  3. $start = microtime(true);  
  4.   
  5. $end = microtime(true);  
  6.   
  7. $time=$end-$start;  
  8.   
  9. //Accurate to ten decimal places, can be adjusted by yourself  
  10.   
  11. echo number_format($time, 10, '.''')." seconds";  
  12.   
  13. ?>  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326126078&siteId=291194637