查看PHP脚本运行所需时间的最佳方法是什么?
我在想这样的事情:
$start_time = time(); //this at the beginning
$end_time = time(); //this at the end
echo = $end_time-$start_time;
Run Code Online (Sandbox Code Playgroud)
但是我怎样才能把它变成对我来说可读并对我有意义的东西呢?
如果你想要比你的时间更进一步的粒度,你需要使用microtime()(返回当前的Unix时间戳和微秒)
<?php
$time_start = microtime(true);
// Sleep for a while
usleep(100);
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "Did nothing in $time seconds\n";
?>
Run Code Online (Sandbox Code Playgroud)
**以后添加**
至于进一步格式化这个结果:
好吧,根据你正在做什么,你通常没有脚本超过一分钟.你绝对不应该超过一个小时.(如果你这样做,你需要问问自己,你在做什么)
考虑到这一点,您只需要简单的计算:
$tmp = floor($time);
$minutes = $tmp / 60;
$seconds = ($tmp % 60) + ($time - $tmp);
$output = 'Script took ';
if ($minutes > 0) $output .= $minutes . ' minutes and ';
$output .= $seconds . ' seconds to complete.';
echo $output;
Run Code Online (Sandbox Code Playgroud)
(这没有经过测试,它可能会被优化,但应该让你朝着正确的方向前进)