我想知道执行一个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
当前回答
$start = microtime(true);
for ($i = 0; $i < 10000; ++$i) {
// do something
}
$total = microtime(true) - $start;
echo $total;
其他回答
看()。
这里有一个非常简单而简短的方法
<?php
$time_start = microtime(true);
//the loop begin
//some code
//the loop end
$time_end = microtime(true);
$total_time = $time_end - $time_start;
echo $total_time; // or whatever u want to do with the time
?>
如果你想以秒为单位显示时间:
<?php
class debugTimer
{
private $startTime;
private $callsCounter;
function __construct()
{
$this->startTime = microtime(true);
$this->callsCounter = 0;
}
public function getTimer(): float
{
$timeEnd = microtime(true);
$time = $timeEnd - $this->startTime;
$this->callsCounter++;
return $time;
}
public function getCallsNumber(): int
{
return $this->callsCounter;
}
}
$timer = new debugTimer();
usleep(100);
echo '<br />\n
' . $timer->getTimer() . ' seconds before call #' . $timer->getCallsNumber();
usleep(100);
echo '<br />\n
' . $timer->getTimer() . ' seconds before call #' . $timer->getCallsNumber();
这样会更清楚
<?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
<?php
// Randomize sleeping time
usleep(mt_rand(100, 10000));
// REQUEST_TIME_FLOAT is available in the $_SERVER superglobal array.
// It contains the timestamp of the start of the request with microsecond precision.
$time = microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"];
echo "Did nothing in $time seconds\n";
?>
这是这个的链接