我想知道执行一个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
当前回答
下面是我用来测量平均时间的脚本
<?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';
其他回答
下面是我用来测量平均时间的脚本
<?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';
如果你想以秒为单位显示时间:
<?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();
你可以通过以下方式使用微时间(true):
把这个放在你的php文件的开头:
//place this before any script you want to calculate time
$time_start = microtime(true);
//你的脚本代码在这里
// do something
把这个放在你的php文件的末尾:
// Display Script End time
$time_end = microtime(true);
//dividing with 60 will give the execution time in minutes other wise seconds
$execution_time = ($time_end - $time_start)/60;
//execution time of the script
echo '<b>Total Execution Time:</b> '.$execution_time.' Mins';
它将在几分钟内输出结果。
<?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";
?>
这是这个的链接
我的方法是使用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毫秒