Home > Backend Development > PHP Tutorial > How to calculate script running time in php?

How to calculate script running time in php?

怪我咯
Release: 2023-03-10 19:04:02
Original
2510 people have browsed it

This article mainly introduces the sharing of simple examples of PHP calculating program running time. Friends who need it can refer to it

First we analyze the principle. If we want to get the program running time, we can run it at the beginning of the program. Define a variable to record the current time, and then record the current time after our program is finished running. The difference between the two is the time it takes to run the program.

Here we introduce the microtime() function. Microtime() is not used much, but we must know this function. It returns the current Unix timestamp and Number of microseconds. For example: echo microtime(); will return: 0.08845800 1376983061. So you can use the explode function to split it into an array with spaces as the identifier, then $starttime[0]=0.08845800 (microseconds), $starttime[1] =1376983061 (the current number of seconds, equivalent to the result obtained by time()).
Sample code:

<?php  
 //程序运行时间
 $starttime = explode(&#39; &#39;,microtime());
 echo microtime();
 /*········以下是代码区·········*/
 for($i=0;$i<1000000;$i++){
  $i;
 }
 /*········以上是代码区·········*/
 //程序运行时间
 $endtime = explode(&#39; &#39;,microtime());
 $thistime = $endtime[0]+$endtime[1]-($starttime[0]+$starttime[1]);
 $thistime = round($thistime,3);
 echo "本网页执行耗时:".$thistime." 秒。".time();
?>
Copy after login

Finally, subtract the two times, and then use the round() function to retain the required decimal places for the execution time. For example, here is the calculation time required to loop one million times: 0.116 seconds, as shown below:

How to calculate script running time in php?

In order to make the program neat, we can write this code into a class , introduce it when used, instantiate this class before the program starts, and then call a method at the end to achieve this function.

The above is the detailed content of How to calculate script running time in php?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template