我想知道执行一个PHP for循环需要多少毫秒。
我知道一个泛型算法的结构,但不知道如何在PHP中实现它:
Begin
init1 = timer(); // where timer() is the amount of milliseconds from midnight
the loop begin
some code
the loop end
total = timer() - init1;
End
我想知道执行一个PHP for循环需要多少毫秒。
我知道一个泛型算法的结构,但不知道如何在PHP中实现它:
Begin
init1 = timer(); // where timer() is the amount of milliseconds from midnight
the loop begin
some code
the loop end
total = timer() - init1;
End
当前回答
我的方法是使用hrtime,它是为性能指标而创建的,它独立于系统时间。Hrtime不受系统时间变化的影响。hrtime自PHP 7.3.0起可用
$start = hrtime(true);
sleep(5); // do something, in your case a loop
$end = hrtime(true);
$eta = $end - $start;
// convert nanoseconds to milliseconds
$eta /= 1e+6;
echo "Code block was running for $eta milliseconds";
输出:
代码块运行了5000.495206毫秒
其他回答
下面是一个返回小数秒的实现(即1.321秒)
/**
* MICROSECOND STOPWATCH FOR PHP
*
* Class FnxStopwatch
*/
class FnxStopwatch
{
/** @var float */
private $start,
$stop;
public function start()
{
$this->start = self::microtime_float();
}
public function stop()
{
$this->stop = self::microtime_float();
}
public function getIntervalSeconds() : float
{
// NOT STARTED
if (empty($this->start))
return 0;
// NOT STOPPED
if (empty($this->stop))
return ($this->stop - self::microtime_float());
return $interval = $this->stop - $this->start;
}
/**
* FOR MORE INFO SEE http://us.php.net/microtime
*
* @return float
*/
private static function microtime_float() : float
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
}
下面是我用来测量平均时间的脚本
<?php
$times = [];
$nbrOfLoops = 4;
for ($i = 0; $i < $nbrOfLoops; ++$i) {
$start = microtime(true);
sleep(1);
$times[] = microtime(true) - $start;
}
echo 'Average: ' . (array_sum($times) / count($times)) . 'seconds';
你可以使用微时间功能。从文档中可以看到:
microtime -以微秒为单位返回当前Unix时间戳 如果get_as_float被设置为TRUE,则microtime()返回一个浮点数,它表示当前时间(以秒为单位),从Unix纪元开始精确到最近的微秒。
使用示例:
$start = microtime(true);
while (...) {
}
$time_elapsed_secs = microtime(true) - $start;
这样会更清楚
<?php
$start = hrtime(true);
while (...) {
}
$duration = hrtime(true) - $start;
echo $duration * 1000 ." -> microseconds". PHP_EOL;
echo $duration * 1000000 ." -> milliseconds". PHP_EOL;
echo $duration * 1e6 ." -> milliseconds". PHP_EOL;
结果
37180000 -> microseconds
37180000000 -> milliseconds
37180000000 -> milliseconds
看()。