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

当前回答

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

其他回答

我的方法是使用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代码的任何部分的执行,很像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上一个独立的、独立的项目

$start = microtime(true);
for ($i = 0; $i < 10000; ++$i) {
    // do something
}
$total = microtime(true) - $start;
echo $total;

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

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

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