通过从 curl_getinfo() 获取详细信息的 cURL 请求时间

Rap*_*tor 6 php performance time curl

我写了一个小脚本来诊断我网站的连接时间,结果如下:

Lookup time:                0.6454ms
Connect time:               1.1611ms
Pretransfer time:           1.1615ms
Redirect time:              0ms
Time to 1st Byte time:      43.397ms
Total time:                 43.445ms
Run Code Online (Sandbox Code Playgroud)

使用的代码如下:

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if(curl_exec($ch) !== false) {
    $info = curl_getinfo($ch);
    echo 'Lookup time: ' . "\t\t" . ($info['namelookup_time'] * 1000) . 'ms' . PHP_EOL;
    echo 'Connect time: ' . "\t\t" . ($info['connect_time'] * 1000) . 'ms' . PHP_EOL;
    echo 'Pretransfer time: ' . "\t" . ($info['pretransfer_time']) . 'ms' . PHP_EOL;
    echo 'Redirect time: ' . "\t\t" . ($info['redirect_time'] * 1000) . 'ms' . PHP_EOL;
    echo 'Time to 1st Byte time: ' . "\t" . ($info['starttransfer_time'] * 1000) . 'ms' . PHP_EOL;
    echo 'Total time: ' . "\t\t" . ($info['total_time'] * 1000) . 'ms' . PHP_EOL;
} else {
    echo 'Error: ' . curl_error($ch);
}
curl_close($ch);
Run Code Online (Sandbox Code Playgroud)

我不太明白上面的结果。

  1. 为什么第一个字节的时间 (TTFB) 时间等于总时间?
  2. 以上时间是累积的吗?如果是,传输时间等于0ms?
  3. 预传输时间是什么意思?

的输出curl_getinfo($ch)

Array
(
    [url] => http://www.example.com/apply.php
    [content_type] => text/html
    [http_code] => 302
    [header_size] => 412
    [request_size] => 88
    [filetime] => -1
    [ssl_verify_result] => 0
    [redirect_count] => 0
    [total_time] => 0.043445
    [namelookup_time] => 0.006454
    [connect_time] => 0.011611
    [pretransfer_time] => 0.011615
    [size_upload] => 0
    [size_download] => 0
    [speed_download] => 0
    [speed_upload] => 0
    [download_content_length] => 0
    [upload_content_length] => 0
    [starttransfer_time] => 0.043397
    [redirect_time] => 0
    [certinfo] => Array
        (
        )

    [redirect_url] => http://www.example.com/index.php
)
Run Code Online (Sandbox Code Playgroud)

Han*_*nky 2

不要浪费时间对请求进行彻底分析。0ms0.5ms电脑的年龄相距甚远;阅读原始数字以避免混淆。

1) 如果 HTTP 请求返回单个资源(而不是完整的网页),则 TTFB 和 Total Time 都是相同的,除非服务器返回的数据量相当大。

2)是的,它是累积的。增加URL返回的数据量,你会看到传输时间也从0ms开始增加

3)服务器接受请求后等待响应的时间