Many times we need to calculate the execution time of a PHP script to know the efficiency of the script and other issues. For example, if there is a large PHP script, we need a method to obtain the script execution time in segments. First introduce the functions to be used:
// 计时函数 function runtime($mode = 0) { static $t; if(!$mode) { $t = microtime(); return; } $t1 = microtime(); list($m0,$s0) = split(" ",$t); list($m1,$s1) = split(" ",$t1); return sprintf("%.3f ms",($s1+$m1-$s0-$m0)*1000); } runtime(); //计时开始 /* // 要计算的PHP脚本 $result = 0; for($i = 0; $i < 100; $i++) { $result += $i; } echo $result; */ echo runtime(1); //计时结束并输出计时结果 runtime(); //计时开始 /* // 要计算的PHP脚本 $result = 0; for($i = 0; $i < 100; $i++) { $result += $i; } echo $result; */ echo runtime(2); //计时结束并输出计时结果
The microtime() function returns the current Unix timestamp and microseconds.
microtime(get_as_float), parameter get_as_float, if the get_as_float parameter is given and its value is equivalent to TRUE, this function will return a floating point number.
<?php echo(microtime()); ?>
If called without optional parameters, this 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) , msec is the microsecond part. Both parts of the string are returned in seconds.
Program output:
0.25139300 1138197510
Now you can calculate the execution time of the PHP script in segments.