我正在尝试制作一个脚本来下载文件的一部分。 只需使用 CURL 和 fread 进行测试,我意识到流式传输过程中的 CURL 比 fread 慢。 为什么?如何加快文件流的 curl ? 我不喜欢使用 fread , fopen 因为我在流媒体过程中需要有限的时间。
这是我的示例代码。
$start = microtime(true);
$f = fopen('http://news.softpedia.com/images/news2/Debian-Turns-15-2.jpeg','r');
$response = fread($f, 3); echo $response.'<br>';
$response = fread($f, 3); echo $response.'<br>';
$response = fread($f, 3); echo $response.'<br>';
$response = fread($f, 3); echo $response.'<br>';
$response = fread($f, 3); echo $response.'<br>';
$stop = round(microtime(true) - $start, 5);
echo "{$stop}s";
exit();
fread/fopen 只需1.1s
$start = microtime(true);
$curl = curl_init('http://news.softpedia.com/images/news2/Debian-Turns-15-2.jpeg');
curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_RANGE, "0-2");
$response = curl_exec($curl);echo $response.'<br>';
curl_setopt($curl, CURLOPT_RANGE, "3-5");
$response = curl_exec($curl);echo $response.'<br>';
curl_setopt($curl, CURLOPT_RANGE, "6-8");
$response = curl_exec($curl);echo $response.'<br>';
curl_setopt($curl, CURLOPT_RANGE, "9-11");
$response = curl_exec($curl);echo $response.'<br>';
curl_setopt($curl, CURLOPT_RANGE, "12-14");
$response = curl_exec($curl);echo $response.'<br>';
curl_close($curl);
$stop = round(microtime(true) - $start, 5);
echo "{$stop}s";
exit();
curl 耗时约 2.5 秒。 如果我采取更多步骤来下载文件的更多部分。 curl 会更慢。
为什么 curl 比较慢?什么解决方案?
最佳答案
它总是比较慢,因为您添加了额外的 HTTP 调用往返。每个 curl_exec 都是一个 HTTP 请求。
关于php - 流式传输文件时 CURL 比 fread 慢?如何加速 CURL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19418877/