我发布了一个可以重现的奇怪行为(至少在 apache2+php5 上)。我不知道我是否做错了,但让我解释一下我试图实现的目标。
我需要发送大块的二进制数据(比如说 30)并在最后分析平均 Kbit/s:
我对每个块输出时间、每个块大小求和,最后执行我的 Kbit/s 计算。
<?php
// build my binary chunk
$var= '';
$o=10000;
while($o--)
{
$var.= pack('N', 85985);
}
// get the size, prepare the memory.
$size = strlen($var);
$tt_sent = 0;
$tt_time = 0;
// I send my chunk 30 times
for ($i = 0; $i < 30; $i++)
{
// start time
$t = microtime(true);
echo $var."\n";
ob_flush();
flush();
$e = microtime(true);
// end time
// the difference should reprenent what it takes to the server to
// transmit chunk to client right ?
// add this chuck bench to the total
$tt_time += round($e-$t,4);
$tt_sent += $size;
}
// total result
echo "\n total: ".(($tt_sent*8)/($tt_time)/1024)."\n";
?>
在上面的这个例子中,它到目前为止工作(在 localhost 上,它通过不同的测试从 7000 到 10000 Kbit/s 振荡)。
现在,假设我想调整传输,因为我知道客户端将有足够的数据块来处理一秒钟。
我决定使用 usleep(1000000) 来标记块传输之间的暂停。
<?php
// build my binary chunk
$var= '';
$o=10000;
while($o--)
{
$var.= pack('N', 85985);
}
// get the size, prepare the memory.
$size = strlen($var);
$tt_sent = 0;
$tt_time = 0;
// I send my chunk 30 times
for ($i = 0; $i < 30; $i++)
{
// start time
$t = microtime(true);
echo $var."\n";
ob_flush();
flush();
$e = microtime(true);
// end time
// the difference should reprenent what it takes to the server to
// transmit chunk to client right ?
// add this chuck bench to the total
$tt_time += round($e-$t,4);
$tt_sent += $size;
usleep(1000000);
}
// total result
echo "\n total: ".(($tt_sent*8)/($tt_time)/1024)."\n";
?>
在最后一个示例中,我不知道为什么,计算出的带宽可以从 72000 Kbit/s 跃升至 1,200,000,这完全不准确/无关紧要。部分问题是每次发送一个块时(在第一次睡眠之后),输出我的块所测量的时间非常低。
我做错了什么?缓冲区输出是否不同步?