php – 通过curl_getinfo()获取详细信息来获取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

使用的代码如下:

$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);

我不太明白上面的结果.

>为什么第一个字节的时间(TTFB)时间等于总时间?
>以上时间累计?如果是,传输时间等于0ms?
> Pretransfer时间是什么意思?

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
)

最佳答案 不要花时间对请求进行彻底的分析. 0ms和0.5ms是计算机相隔的年龄;阅读原始数字以避免混淆.

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

2)是的,它是累积的.增加URL返回的数据量,您将看到传输时间也将从0ms增加

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

点赞