在while循环中使用time()

时间:2017-12-09 11:17:42

标签: php

对于学校作业,我们需要编写一个计算1秒钟的PHP脚本。

我写的以下代码应该完全符合我的想法:

String

但是,每当我运行这个或任何类似于在while循环中使用time()函数的PHP脚本时,当我尝试访问该页面时,我会从服务器收到502错误请求。

2 个答案:

答案 0 :(得分:2)

您的代码不起作用(不会精确计算一秒),因为time()的粒度为一秒,并且您无法保证您的页面恰好位于页面的下方第二。所以你需要同步。

要清楚,想象一下多次调用time(),并且为了清晰起见,让HH:MM:SS而不是Unix时间戳假设time()输出:

Code
print time()
print time()
print time()
...

Output:
01:15:17
01:15:17
01:15:17
...
01:15:18
01:15:18
01:15:18
...

你的程序当前可能无法正常工作,因为即使在循环运行的时间很短的情况下,它也会产生大量的输出(如上所示,time()仍然是"有效"最多一秒钟,并且在那个时间循环可以执行 lot 次。如果PHP进程存在某种资源限制,则可能会导致进程超过其配额,从而导致502错误。您可以通过从循环中删除echo来检查,最后只添加echo "Done."

您想要计算time()从01:15:17过渡到01:15:18的瞬间,直到它再次转换到01:15:19的瞬间。 那些时刻将间隔一秒钟。

您需要做的是:

$startTijd = time()+1; // It is now maybe 01:15:17.93. We want to start
                       // counting at 01:15:18, so we need to wait for it.
while($startTijd !== time()) {
    // Do nothing except maybe a very brief sleep to save CPU
    usleep(5); // this is optional anyway.
}
// It is now 01:15:18.000003 and $startTijd is 01:15:18
$teller = 0;
// time() will remain equal to 01:15:18 for one second,
// while wall clock time increases from 01:15:18.000003 to 01:15:18.999999
while ($startTijd == time()) {
    // Don't output anything here
    $teller++;
}
// New transition detected.
// It is now e.g. 01:15:19.000137 and time() says 01:15:19.
echo 'Iteratie: ' . $teller . '<br>';

或者,您可以使用microtime(true)

$teller = 0;
$endTijd = microtime(true) + 1.0;
while ($endTijd >= microtime(true)) {
    // Don't output anything here
    $teller++;
}
echo 'Iteratie: ' . $teller . '<br>';

答案 1 :(得分:1)

你的代码毫无意义......只有当你的计算机速度足够快时,你的声明才会成立。

$startTijd = 100; # you set here the time represented by a number

while(100 == time() #101) { # here time is some milliseconds or seconds in the future

所以一秒钟之后停下来让你的感觉不那么明显。然后使用

while(true) {

并以条件洞察while循环停止。