掃二維碼與項(xiàng)目經(jīng)理溝通
我們在微信上24小時期待你的聲音
解答本文疑問/技術(shù)咨詢/運(yùn)營咨詢/技術(shù)建議/互聯(lián)網(wǎng)交流
最近工作中遇到一個問題,某個請求的響應(yīng)特別慢,因此我就希望有一種方法能夠分析到底請求的哪一步耗時比較長,好進(jìn)一步找到問題的原因。在網(wǎng)絡(luò)上搜索了一下,發(fā)現(xiàn)了一個非常好用的方法, curl 命令就能幫你分析請求的各個部分耗時。

curl 命令提供了 -w 參數(shù),這個參數(shù)在 manpage 是這樣解釋的:
- -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 轉(zhuǎn)義字符。提供的變量很多,比如 status_code 、 local_port 、 size_download 等等,這篇文章我們只關(guān)注和請求時間有關(guān)的變量(以 time_ 開頭的變量)。
先往文本文件 curl-format.txt 寫入下面的內(nèi)容:
- ~ 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
那么這些變量都是什么意思呢?我解釋一下:
我們先看看一個簡單的請求,沒有重定向,也沒有 SSL 協(xié)議的時間:
- ~ curl -w "@curl-format.txt" -o /dev/null -s -L "http://cizixs.com"
- time_namelookup: 0.012
- time_connect: 0.227
- time_appconnect: 0.000
- time_redirect: 0.000
- time_pretransfer: 0.227
- time_starttransfer: 0.443
- ----------
- time_total: 0.867
可以看到這次請求各個步驟的時間都打印出來了,每個數(shù)字的單位都是秒(seconds),這樣可以分析哪一步比較耗時,方便定位問題。這個命令各個參數(shù)的意義:
從這個輸出,我們可以算出各個步驟的時間:
來個比較復(fù)雜的,訪問某度首頁,帶有中間有重定向和 SSL 協(xié)議:
- ~ curl -w "@curl-format.txt" -o /dev/null -s -L "https://baidu.com"
- time_namelookup: 0.012
- time_connect: 0.018
- time_appconnect: 0.328
- time_redirect: 0.356
- time_pretransfer: 0.018
- time_starttransfer: 0.027
- ----------
- time_total: 0.384
可以看到 time_appconnect 和 time_redirect 都不是 0 了,其中 SSL 協(xié)議處理時間為 328-18=310ms 。而且 pretransfer 和 starttransfer 的時間都縮短了,這是重定向之后請求的時間。

我們在微信上24小時期待你的聲音
解答本文疑問/技術(shù)咨詢/運(yùn)營咨詢/技術(shù)建議/互聯(lián)網(wǎng)交流