gpt4 book ai didi

php - 重复使用相同的 curl 句柄。性能大幅提升?

转载 作者:IT王子 更新时间:2023-10-29 01:17:53 26 4
gpt4 key购买 nike

在 PHP 脚本中,我对不同的 URL 执行了很多不同的 curl GET 请求(一百个)。

重用 curl_init 中的相同句柄是否会提高性能,或者与请求的响应时间相比可以忽略不计?

我问这个是因为在当前的架构中,保持相同的句柄并不容易。

最佳答案

交叉发布自 Should I close cURL or not?因为我认为它在这里也很重要。

我尝试通过对每个请求使用新句柄并将相同句柄与以下代码一起使用来对 curl 进行基准测试:

ob_start(); //Trying to avoid setting as many curl options as possible
$start_time = microtime(true);
for ($i = 0; $i < 100; ++$i) {
$rand = rand();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.google.com/?rand=" . $rand);
curl_exec($ch);
curl_close($ch);
}
$end_time = microtime(true);
ob_end_clean();
echo 'Curl without handle reuse: ' . ($end_time - $start_time) . '<br>';

ob_start(); //Trying to avoid setting as many curl options as possible
$start_time = microtime(true);
$ch = curl_init();
for ($i = 0; $i < 100; ++$i) {
$rand = rand();
curl_setopt($ch, CURLOPT_URL, "http://www.google.com/?rand=" . $rand);
curl_exec($ch);
}
curl_close($ch);
$end_time = microtime(true);
ob_end_clean();
echo 'Curl with handle reuse: ' . ($end_time - $start_time) . '<br>';

得到如下结果:

Curl without handle reuse: 8.5690529346466
Curl with handle reuse: 5.3703031539917

因此,当多次连接到同一台服务器时,重用同一个句柄实际上可以显着提高性能。我尝试连接到不同的服务器:

$url_arr = array(
'http://www.google.com/',
'http://www.bing.com/',
'http://www.yahoo.com/',
'http://www.slashdot.org/',
'http://www.stackoverflow.com/',
'http://github.com/',
'http://www.harvard.edu/',
'http://www.gamefaqs.com/',
'http://www.mangaupdates.com/',
'http://www.cnn.com/'
);
ob_start(); //Trying to avoid setting as many curl options as possible
$start_time = microtime(true);
foreach ($url_arr as $url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_exec($ch);
curl_close($ch);
}
$end_time = microtime(true);
ob_end_clean();
echo 'Curl without handle reuse: ' . ($end_time - $start_time) . '<br>';

ob_start(); //Trying to avoid setting as many curl options as possible
$start_time = microtime(true);
$ch = curl_init();
foreach ($url_arr as $url) {
curl_setopt($ch, CURLOPT_URL, $url);
curl_exec($ch);
}
curl_close($ch);
$end_time = microtime(true);
ob_end_clean();
echo 'Curl with handle reuse: ' . ($end_time - $start_time) . '<br>';

得到如下结果:

Curl without handle reuse: 3.7672290802002
Curl with handle reuse: 3.0146431922913

仍然是相当可观的性能提升。

关于php - 重复使用相同的 curl 句柄。性能大幅提升?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3787002/

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