【发布时间】:2017-03-13 08:24:46
【问题描述】:
我在 localhost 上通过 URL 获得服务响应。当使用 CURL 并使用“localhost”作为域名时,第一个请求大约需要 150 毫秒,第二个请求需要 2 毫秒。当使用 IP 而不是“localhost”时,两个 CURL 请求都需要 2 毫秒。使用file_get_contents 时,无论是“localhost”还是IP,它总是大约3ms。
即使对于本地主机,什么也会导致这种延迟?
这里是测试代码:
$instance['port'] = 8192;
$instance['hostname' ] = 'localhost';
//$instance['hostname' ] = '127.0.0.1';
/* file_get_contents */
$time = microtime(true);
$response = file_get_contents('http://'.$instance['hostname' ].':'.$instance['port'].'/file1.txt');
$queryTime = microtime(true) - $time;
echo "file_get_contents time: ".$queryTime."<br>";
$time = microtime(true);
$response = file_get_contents('http://'.$instance['hostname' ].':'.$instance['port'].'/file2.txt');
$queryTime = microtime(true) - $time;
echo "file_get_contents time: ".$queryTime."<br><br>";
/* CURL */
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://'.$instance['hostname' ].':'.$instance['port'].'/file1.txt');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$time = microtime(true);
curl_exec($ch);
$queryTime = microtime(true) - $time;
echo "CURL time: ".$queryTime."<br>";
curl_setopt($ch, CURLOPT_URL, 'http://'.$instance['hostname' ].':'.$instance['port'].'/file2.txt');
$time = microtime(true);
curl_exec($ch);
$queryTime = microtime(true) - $time;
echo "CURL time: ".$queryTime."<br><br>";
curl_close($ch);
回复:
file_get_contents time: 0.0029559135437012
file_get_contents time: 0.0030159950256348
CURL time: 0.15396809577942
CURL time: 0.002269983291626
当使用 IP 而不是 localhost 时,响应如下:
file_get_contents time: 0.0025560855865479
file_get_contents time: 0.0034060478210449
CURL time: 0.0026850700378418
CURL time: 0.0027031898498535
【问题讨论】: