我想知道执行一个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
当前回答
下面是一个返回小数秒的实现(即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
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();
您可以使用$_SERVER超全局数组中的REQUEST_TIME。从文档中可以看到:
REQUEST_TIME 请求开始的时间戳。(自PHP 5.1.0起可用。) REQUEST_TIME_FLOAT 请求开始的时间戳,具有微秒精度。(自PHP 5.4.0起可用。)
这样就不需要在脚本的开头保存时间戳。你可以简单地做:
<?php
// Do stuff
usleep(mt_rand(100, 10000));
// At the end of your script
$time = microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"];
echo "Did stuff in $time seconds\n";
?>
在这里,$time将包含自脚本开始以来所经过的时间,以秒为单位,具有微秒精度(例如。1.341为1秒和341微秒)
更多信息:
PHP文档:$_SERVER变量和microtime函数
你可以使用微时间功能。从文档中可以看到:
microtime -以微秒为单位返回当前Unix时间戳 如果get_as_float被设置为TRUE,则microtime()返回一个浮点数,它表示当前时间(以秒为单位),从Unix纪元开始精确到最近的微秒。
使用示例:
$start = microtime(true);
while (...) {
}
$time_elapsed_secs = microtime(true) - $start;
看()。
$start = microtime(true);
for ($i = 0; $i < 10000; ++$i) {
// do something
}
$total = microtime(true) - $start;
echo $total;