curl 命令提供了 -w 參數,解釋如下
-w, --write-out Make curl display information on stdout after a completed transfer. The format is a string that may contain plain text mixed with any number of variables. The format can be specified as a literal "string", or you can have curl read the format from a file with "@filename" and to tell curl to read the format from stdin you write "@-". The variables present in the output format will be substituted by the value or text that curl thinks fit, as described below. All variables are specified as %{vari‐ able_name} and to output a normal % you just write them as %%. You can output a newline by using \n, a carriage return with \r and a tab space with \t.
它能夠按照指定的格式打印某些信息,里面可以使用某些特定的變量,而且支持 \n 、 \t 和 \r 轉義字符。提供的變量很多,比如 status_code 、 local_port 、 size_download 等等,這篇文章我們只關注和請求時間有關的變量(以 time_ 開頭的變量)
文本文件 curl-format.txt 寫入下面的內容:
[root@node ~]# cat curl-format.txt time_namelookup: %{time_namelookup}\n time_connect: %{time_connect}\n time_appconnect: %{time_appconnect}\n time_redirect: %{time_redirect}\n time_pretransfer: %{time_pretransfer}\n time_starttransfer: %{time_starttransfer}\n ----------\n time_total: %{time_total}\n #變量解釋如下 time_namelookup :DNS 域名解析的時候,就是把 https://zhihu.com 轉換成 ip 地址的過程 time_connect :TCP 連接建立的時間,就是三次握手的時間 time_appconnect :SSL/SSH 等上層協議建立連接的時間,比如 connect/handshake 的時間 time_redirect :從開始到最后一個請求事務的時間 time_pretransfer :從請求開始到響應開始傳輸的時間 time_starttransfer :從請求開始到第一個字節將要傳輸的時間 time_total :這次請求花費的全部時間
看一下命令的輸出
[root@node ~]# curl -w "@curl-format.txt" -o /dev/null -s -L "http://www.52py.com.cn" time_namelookup: 0.124 time_connect: 0.132 time_appconnect: 0.257 time_redirect: 0.282 time_pretransfer: 0.257 time_starttransfer: 15.315 ---------- time_total: 15.605
可以看到這次請求各個步驟的時間都打印出來了,每個數字的單位都是秒(seconds),這樣可以分析哪一步比較耗時,方便定位問題。這個命令各個參數的意義:
- -w :從文件中讀取要打印信息的格式
- -o /dev/null :把響應的內容丟棄,不關心,只關心請求的耗時情況
- -s :不要打印進度條
從上面的輸出,我們可以算出各個步驟的時間
- DNS 查詢:124ms
- TCP 連接時間:pretransfter(257) - namelookup(124) = 133ms
- SSL 協議處理時間: appconnect(257) - connect(132) = 125ms
- 服務器處理時間:starttransfter(15.315) - pretransfer(257) = 15.058s
- 內容傳輸時間:total(15.605) - starttransfer(15.315) = 290ms