gpt4 book ai didi

php - fsockopen 通常很慢吗?

转载 作者:搜寻专家 更新时间:2023-10-31 21:15:53 25 4
gpt4 key购买 nike

我正在尝试在 PHP 中执行下行带宽速度测试。我不知道为什么 wget 会以 400 Mbps 的速度下载 1 MB 的数据,而 fsockopen 会以 170 Mbps 的速度下载。我正在使用 fsockopen,因为所有服务器都支持它。

有人知道为什么吗? 400 Mbps 与 170 Mbps 差别很大。

是否有更好的性能选择?

<?php
$url = 'http://ftp.sunet.se/pub/Linux/distributions/ubuntu/ubuntu/dists/hardy-backports/Contents-i386.gz';
$size = 1024*1024; // Get amount of bytes

$parts = parse_url($url);
$fp = fsockopen($parts['host'], isset($parts['port']) ? $parts['port'] : 80, $errno, $errstr, 30);

if (!$fp) throw new Exception("Problem with $url, $errstr");

$out = "GET " . $parts['path'] ." HTTP/1.1\r\n"
. "Host: ". $parts['host'] ."\r\n"
. "Connection: Close\r\n\r\n";

fwrite($fp, $out);

$found_body = false;
$response = '';
$start = microtime(true);
$timeout = 30;

while (!feof($fp)) {
if ((microtime(true) - $start) > $timeout) break;
if (strlen($response) > $size) break;
//$row = fgets($fp, 128); // Grab block of 128
$row = fgets($fp);
if ($found_body) {
$response .= $row;
} else if ($row == "\r\n") {
$found_body = true;
$tsStart = microtime(true);
continue;
}
}

$time_elapsed = microtime(true) - $tsStart;

$speed = strlen($response) / $time_elapsed * 8 / 1000000;

echo round($speed, 2) . ' Mbps ('. strlen($response) .' bytes in '. round($time_elapsed, 3) .' s)<br />';

?>

最佳答案

慢的不是 fsockopen - 通常是 PHP。尝试增加 fgets() 调用中的缓冲区大小,并使用正则表达式查找 header 的末尾。使用您当前的代码,您执行读取循环的次数过多,网络 IO 不再是您的瓶颈。

关于php - fsockopen 通常很慢吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8974404/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com