在没有任何输出的情况下使用PHP访问URL的最快方法是什么?
我使用file_get_contents和CURL对下面的代码进行了测试,但结果不稳定且非常接近。
function abtest()
{
$arr_to_return = array();
$t = microtime(true);
file_get_contents('http://127.0.0.1/test.html');
$e = microtime(true);
$arr_to_return['file_get_contents'] = $e-$t;
$t = microtime(true);
$handle = curl_init('http://127.0.0.1/test.html');
curl_setopt($handle, CURLOPT_NOBODY, TRUE);
curl_exec($handle);
curl_close($handle);
$e = microtime(true);
$arr_to_return['curl'] = $e-$t;
return $arr_to_return;
}
$limit = 20;
$count = 0;
$result = array();
$filegetcontents = 0;
$curl = 0;
do{
$test = abtest();
$result['file_get_contents'][] = $test['file_get_contents'];
$filegetcontents += $test['file_get_contents'];
$result['curl'][] = $test['curl'];
$curl += $test['curl'];
$count++;
} while ( $count < $limit);
echo '<pre>';
print_r($result);
echo '</pre>';
echo 'Average: file_get_contents ('.($filegetcontents/$limit).') curl ('.($curl/$limit).')';
根据建议,我将它放入一个函数中,并在localhost上使用直接IP循环20次。
结果如下:
Array
(
[file_get_contents] => Array
(
[0] => 0.0055451393127441
[1] => 0.0056819915771484
[2] => 0.0056838989257812
[3] => 0.014945983886719
[4] => 0.014636993408203
[5] => 0.014842987060547
[6] => 0.0053179264068604
[7] => 0.015022039413452
[8] => 0.014861106872559
[9] => 0.015033960342407
[10] => 0.015429973602295
[11] => 0.015249013900757
[12] => 0.01471996307373
[13] => 0.015311002731323
[14] => 0.0054020881652832
[15] => 0.015032052993774
[16] => 0.0051870346069336
[17] => 0.014680147171021
[18] => 0.014776945114136
[19] => 0.015046119689941
)
[curl] => Array
(
[0] => 0.0013649463653564
[1] => 0.0017318725585938
[2] => 0.0013041496276855
[3] => 0.0013928413391113
[4] => 0.0013279914855957
[5] => 0.0013871192932129
[6] => 0.011061906814575
[7] => 0.0013771057128906
[8] => 0.010823011398315
[9] => 0.0015439987182617
[10] => 0.0015928745269775
[11] => 0.0014979839324951
[12] => 0.0016429424285889
[13] => 0.011864900588989
[14] => 0.0015189647674561
[15] => 0.0014710426330566
[16] => 0.0014939308166504
[17] => 0.001460075378418
[18] => 0.011038064956665
[19] => 0.010931015014648
)
)
Average: file_get_contents (0.012120318412781) curl (0.0038913369178772)
在大多数情况下,似乎CURL的结果优于file_get_contents。除了上面以外,还有更快的方法吗?