谁能告诉我为什么当我运行具有以下内容的脚本然后在 5 秒后停止它时我需要将耗时除以 2 以获得正确的脚本执行时间?
ignore_user_abort(true); set_time_limit(0);
$begin_time = microtime(true);
$elapsed_time = 0;
while(!connection_aborted()) {
echo ' ';
flush();
usleep(1000000);
}
$elapsed_time = microtime(true) - $begin_time;
$timer_seconds = $elapsed_time; //10 seconds
$timer_seconds = $elapsed_time / 2; //5 seconds
/*I am writing to a DB - but you can use this to test */
$fp = fopen('times.txt', 'w');
fwrite($fp, 'Time Elapsed: '.$timer_seconds);
fclose($fp);
请随意尝试代码,因为它让我困惑为什么 $elapsed_time
需要除以二。也许我误解了什么?
感谢大家的帮助
更新
我已经更新了代码,这样任何人都可以尝试这个,它会写入一个文本文件以查看输出。
最佳答案
实验:
原始代码的重大变化:
1) 使用 implicit_flush 并在执行任何操作之前刷新所有缓冲区。
2) 代码输出迭代次数和 1023 字节的其他数据,而不是只输出一个空格,以告诉浏览器我们有大量的输出要显示。一个普通的已知技巧。
3) 除了在输出文本文件中保存时间外,它还保存了代码运行的总迭代次数。
使用的代码:
<?php
// Tricks to allow instant output
@ini_set('implicit_flush', 1);
for ($i = 0; $i < ob_get_level(); $i++)
ob_end_flush();
ob_implicit_flush(1);
//Your Code starts here
ignore_user_abort(true);
set_time_limit(0);
$begin_time = microtime(true);
$elapsed_time = 0;
while(!connection_aborted())
{
//this I changed, so that a looooong string is outputted
echo $i++.str_repeat(' ',1020).'<br/>';
flush();
usleep(1000000);
}
$elapsed_time = microtime(true) - $begin_time;
$timer_seconds = $elapsed_time; //10 seconds
//Writes to file the number of ITERATIONS too along with time
$fp = fopen('4765107.txt', 'w');
fwrite($fp, 'Time Elapsed: '.$timer_seconds);
fwrite($fp, "\nIterations: ".$i);
fclose($fp);
?>
现场演示:
现在,这是要运行的代码: http://work.sktnetwork.com/so/4765107.php
这是它生成的 .TXT 文件: http://work.sktnetwork.com/so/4765107.txt
我得到了什么:
1) 当代码运行 10 次迭代并单击浏览器上的停止按钮时,输出文件显示 13 次迭代,耗时约 13.01 秒。
2) 当代码运行 20 次迭代并单击浏览器上的停止按钮时,输出文件显示 23 次迭代,耗时约 23.01 秒。
推论与结论:
1) 脚本实际上不会在单击“停止”按钮时停止,而是在单击它 2-4 秒后停止。因此,浏览器中出现的迭代次数更多。
2) 迭代次数与执行所需的秒数相同,如输出文件所示。
因此,没有错误,显然也没有错误,只是单击“停止”按钮和脚本实际停止之间的延迟时间。
注意事项:
1)服务器:一台Linux VPS。
2) 测试客户端:Firefox 和 Chrome。
3) 由于脚本在单击“停止”后 2-4 秒结束,因此输出文件需要大约 3-4 秒才能为当前测试更新。
关于php - 你能找出这个 PHP 计时问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4765107/