我想知道执行一个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

你可以使用微时间功能。从文档中可以看到:

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;

您的想法是正确的,不过microtime()函数可以提供更精确的计时。

如果循环内的内容是快速的,则可能的表观消耗时间将为零。如果是这样,则围绕该代码封装另一个循环并重复调用它。请确保将差值除以迭代次数,以得到每一次的时间。我已经分析了需要10,000,000次迭代才能获得一致、可靠的计时结果的代码。


创建文件loadtime.php

<?php
class loadTime{
    private $time_start     =   0;
    private $time_end       =   0;
    private $time           =   0;
    public function __construct(){
        $this->time_start= microtime(true);
    }
    public function __destruct(){
        $this->time_end = microtime(true);
        $this->time = $this->time_end - $this->time_start;
        echo "Loaded in $this->time seconds\n";
    }
}

而不是在<?PHP: loadtime.php美元loadtime = new loadtime ();

当页面加载结束时,会写“加载在x秒内”


你可以通过以下方式使用微时间(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';

它将在几分钟内输出结果。


您可以使用$_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函数


这里有一个函数,可以计时PHP代码的任何部分的执行,很像Python的timeit模块:https://gist.github.com/flaviovs/35aab0e85852e548a60a

如何使用:

include('timeit.php');
const SOME_CODE = '
        strlen("foo bar");
';
$t = timeit(SOME_CODE);
print "$t[0] loops; $t[2] per loop\n";

结果:

$ php x.php 
100000 loops; 18.08us per loop

免责声明:我是本文主旨的作者

EDIT: timeit现在是https://github.com/flaviovs/timeit上一个独立的、独立的项目


这里有一个非常简单而简短的方法

<?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
?>

下面是一个返回小数秒的实现(即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);
    }
}

我想分享一下我的功能。希望能帮你节省时间。

它最初用于跟踪基于文本的脚本的时间,因此输出是文本形式的。但如果您愿意,可以轻松地将其修改为HTML。

它将为您计算自脚本开始和在每个步骤中花费了多少时间。它将所有输出格式化为3个精度小数。(精确到毫秒。)

一旦将它复制到脚本的顶部,所要做的就是将recordTime函数调用放在想要计时的每个片段之后。

复制到你的脚本文件的顶部:

$tRecordStart = microtime(true);
header("Content-Type: text/plain");
recordTime("Start");

function recordTime ($sName) {
  global $tRecordStart;
  static $tStartQ;
  $tS = microtime(true);
  $tElapsedSecs = $tS - $tRecordStart;
  $tElapsedSecsQ = $tS - $tStartQ;
  $sElapsedSecs = str_pad(number_format($tElapsedSecs, 3), 10, " ", STR_PAD_LEFT);
  $sElapsedSecsQ = number_format($tElapsedSecsQ, 3);
  echo "//".$sElapsedSecs." - ".$sName;
  if (!empty($tStartQ)) echo " In ".$sElapsedSecsQ."s";
  echo "\n";
  $tStartQ = $tS;
}

想要记录时间的流逝,你可以这样做:

recordTime("What We Just Did")

例如:

recordTime("Something Else")
//Do really long operation.
recordTime("Really Long Operation")
//Do a short operation.
recordTime("A Short Operation")
//In a while loop.
for ($i = 0; $i < 300; $i ++) {
  recordTime("Loop Cycle ".$i)
}

给出如下输出:

//     0.000 - Start
//     0.001 - Something Else In 0.001s
//    10.779 - Really Long Operation In 10.778s
//    11.986 - A Short Operation In 1.207s
//    11.987 - Loop Cycle 0 In 0.001s
//    11.987 - Loop Cycle 1 In 0.000s
...
//    12.007 - Loop Cycle 299 In 0.000s

希望这能帮助到一些人!


如果你想以秒为单位显示时间:

<?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

$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';

您可以用一个函数找到以秒为单位的执行时间。

// ampersand is important thing here
function microSec( & $ms ) {
    if (\floatval( $ms ) == 0) {
        $ms = microtime( true );
    }
    else {
        $originalMs = $ms;
        $ms = 0;
        return microtime( true ) - $originalMs;
    }
}

// you don't have to define $ms variable. just function needs
// it to calculate the difference.
microSec($ms);
sleep(10);
echo microSec($ms) . " seconds"; // 10 seconds

for( $i = 0; $i < 10; $i++) {
    // you can use same variable everytime without assign a value
    microSec($ms);
    sleep(1);
    echo microSec($ms) . " seconds"; // 1 second
}

for( $i = 0; $i < 10; $i++) {
    // also you can use temp or useless variables
    microSec($xyzabc);
    sleep(1);
    echo microSec($xyzabc) . " seconds"; // 1 second
}

我的方法是使用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毫秒


<?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";
?>

这是这个的链接


这样会更清楚

<?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