通过代码的执行时间,可以判断代码的执行效率,进一步考虑代码的优化,提升自己的编码能力。
//设置当前时区
date_default_timezone_set('Asia/Shanghai');
//获取当前时区
echo date_default_timezone_get();
echo '</br></br>';
//脚本执行时间计算函数
function runtime($start = null,$end = null){
static $cache = [];
if(is_null($start)){
return $cache;
}else if(is_null($end)){
return $cache[$start] = microtime(true);
}else{
$end =$cache[$end] ?? microtime(true);
return round($end-$cache[$start],3);
}
}
for循环与while循环的效率比较
//for循环执行时间
runtime('forstart');
for($i=0;$i<2000000;$i++){
}
runtime('forend');
echo 'for循环执行时间:'.runtime('forstart','forend');
echo '</br></br>';
//while循环执行时间
runtime('while_start');
$n = 0;
while($n <2000000){
$n++;
}
runtime('while_end');
echo 'while循环执行时间:'.runtime('while_start','while_end');
echo '</br></br>';
echo '总执行时间:'.runtime('forstart','while_end');
执行结果:在百万级循环中,for循环比while循环执行效率低。