Home  >  Article  >  Backend Development  >  Sharing a simple example of calculating program running time in PHP_PHP Tutorial

Sharing a simple example of calculating program running time in PHP_PHP Tutorial

WBOY
WBOYOriginal
2016-07-13 10:30:051058browse

First of all, let’s analyze the principle. If we want to get the running time of the program, we can define a variable to record the current time when the program first runs, and then record the current time after our program has finished running. The difference between the two is The time it took for the program to run.

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

Sample code:

Copy code The code is as follows:

//Program running time
$starttime = explode(' ',microtime());
echo microtime();

/*·········The following is the code area·········*/
for($i=0;$i<1000000;$i++){
$i;
}
/*·········The above is the code area·········*/

//Program running time
$endtime = explode(' ',microtime());
$thistime = $endtime[0]+$endtime[1]-($starttime[0]+$ starttime[1]);
$thistime = round($thistime,3);
echo "The execution of this webpage takes: ".$thistime." seconds.".time();
?> ;


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:

Sharing a simple example of calculating program running time in PHP_PHP Tutorial

For the sake of program neatness, 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.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/768128.htmlTechArticleFirst we analyze the principle. If we want to get the program running time, we can define a variable when the program first runs. Write down the current time and wait until our program finishes running...
Statement:
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