Home > Article > Backend Development > Sharing a simple example of calculating program running time in PHP_PHP Tutorial
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:
/*·········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();
?> ;
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.