Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php fsockopen通常慢吗?_Php_Performance_Bandwidth_Fsockopen - Fatal编程技术网

Php fsockopen通常慢吗?

Php fsockopen通常慢吗?,php,performance,bandwidth,fsockopen,Php,Performance,Bandwidth,Fsockopen,我正在尝试用PHP执行下游带宽速度测试。我不知道为什么wget会以400 Mbps的速度下载1 Mbyte数据,而fsockopen则以170 Mbps的速度下载。我使用fsockopen,因为它在所有服务器上都受支持 有人知道为什么吗?400Mbps和170Mbps是一个很大的区别 有更好的性能选择吗 <?php $url = 'http://ftp.sunet.se/pub/Linux/distributions/ubuntu/ubuntu/dists/hardy-back

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

有人知道为什么吗?400Mbps和170Mbps是一个很大的区别

有更好的性能选择吗

<?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()
调用中的缓冲区大小,并使用正则表达式查找头的结尾。使用当前代码,您执行读取循环的次数太多,网络IO不再是您的瓶颈。

allow\u url\u fopen不支持这一点=false@user1135440:如果
allow\u url\u fopen
设置为
false
,则OP也无法以这种方式使用
fopen()。由于他抱怨性能,而不是PHP致命错误,很明显,他的
allow\u url\u fopen
没有设置为
false
。allow\u url\u fopen不适用于fsockopen。这是一个很好的答案,但并没有改善任何情况。事实上,最理想的数据包大小是64-128。高于或低于此值会使性能急剧恶化。我运行了10次测试,结果都是一样的。由于您实际上没有使用repsonse,请尝试在读取数据后将其丢弃,以避免通过执行字符串concats不断重新分配内存。这也可能是燃烧时间,而不是将响应存储在缓冲区I do$response_amount+=strlen(row);。我自发地觉得它可能已经获得了5-10%的性能提升。但是,性能有时会变慢。这取决于单个调用本身。这可能是向前迈出的一步。好主意。