Home  >  Article  >  Backend Development  >  PHP calculates code execution time-consuming code and fixes common online errors_PHP Tutorial

PHP calculates code execution time-consuming code and fixes common online errors_PHP Tutorial

WBOY
WBOYOriginal
2016-07-21 15:29:57881browse

Copy code The code is as follows:

$t1 = explode(' ', microtime());
// ... Execute the code...
$t2 = explode(' ', microtime());
echo ($t2[1]-$t1[1]).'s '.($t2[0]- $t1[0]).'ms';

In fact, after a little try, you can find that this code has a serious problem. Although the time obtained by t2 is definitely greater than that of t1, it does not mean that , its number of microseconds must be greater than the number of microseconds of t1. Therefore, if subtracted directly, the ms part may be a negative number. Therefore, I changed it slightly myself, and the code is as follows:
Copy code The code is as follows:

$t1 = microtime(true);
//... Execute the code...
$ t2 = microtime(true);
echo 'time consuming'.round($t2-$t1,3).'seconds';

Say briefly. microtime() If you bring true parameter, the return will be a floating point type. In this way, t1 and t2 get two floating point numbers, and after subtracting, the difference between them is obtained. Since the number of digits of the floating point is very long, or it is uncertain, so use A round() takes out 3 digits after the decimal point. In this way, our goal is achieved~

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/323343.htmlTechArticleCopy the code The code is as follows: $t1 = explode(' ', microtime()); // ... Execute Code... $t2 = explode(' ', microtime()); echo ($t2[1]-$t1[1]).'s '.($t2[0]-$t1[0]). 'ms'; Actually give it a try...
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