如何使用cURL獲得請(qǐng)求和響應(yīng)時(shí)間?
本文轉(zhuǎn)載自微信公眾號(hào)「精益碼農(nóng)」,作者StackOverflow 。轉(zhuǎn)載本文請(qǐng)聯(lián)系精益碼農(nóng)公眾號(hào)。
cURL在我的眼里,就是一個(gè)httpClient手辦,老伙計(jì)們知道怎么獲得cURL請(qǐng)求的具體耗時(shí)嗎? ??
cURL支持格式化輸出請(qǐng)求的詳細(xì)信息(請(qǐng)參閱cURL手冊(cè)頁的-w、–write out
如題,我們只關(guān)注如何知曉cURL請(qǐng)求的時(shí)間細(xì)節(jié), 下面時(shí)間以s為單位。
1. 創(chuàng)建一個(gè)文本文件curl-format.txt, 粘貼下面內(nèi)容
- time_namelookup: %{time_namelookup}s\n
- time_connect: %{time_connect}s\n
- time_appconnect: %{time_appconnect}s\n
- time_pretransfer: %{time_pretransfer}s\n
- time_redirect: %{time_redirect}s\n
- ime_starttransfer: %{time_starttransfer}s\n
- ----------\n
- time_total: %{time_total}s\n
2.發(fā)起請(qǐng)求
url -w "@curl-format.txt" -o /dev/null -s "http://wordpress.com/"
在windows機(jī)器上是curl -w "@curl-format.txt" -o NUL -s "http://wordpress.com/"
旁白解釋
-w "@curl-format.txt" 通知cURL使用格式化的輸出文件
-o /dev/null 將請(qǐng)求的輸出重定向到/dev/null
-s 通知cURL不顯示進(jìn)度條
"http://wordpress.com/" 是我們請(qǐng)求的URL,請(qǐng)使用引號(hào)包圍(尤其當(dāng)你的URL包含&查詢字符串)
文本輸出
- time_namelookup: 0.001s
- time_connect: 0.037s
- time_appconnect: 0.000s
- time_pretransfer: 0.037s
- time_redirect: 0.000s
- time_starttransfer: 0.092s
- ----------
- time_total: 0.164s
輸出的啥意思呢?我解釋一下:
- time_namelookup:DNS 域名解析的時(shí)間,就是把http://wordpress.com 轉(zhuǎn)換成ip地址的過程
- time_connect:TCP 連接建立的時(shí)間,就是三次握手的時(shí)間
- time_appconnect:SSL/SSH等上層協(xié)議建立連接的時(shí)間,比如 connect/handshake 的時(shí)間
- time_pretransfer:從請(qǐng)求開始到響應(yīng)開始傳輸?shù)臅r(shí)間
- time_starttransfer:從請(qǐng)求開始到第一個(gè)字節(jié)將要傳輸?shù)臅r(shí)間
- time_total:這次請(qǐng)求花費(fèi)的全部時(shí)間
制作成Linux/Mac快捷命令(alise 別名)
alias curltime="curl -w \"@$HOME/.curl-format.txt\" -o /dev/null -s "
制作成Linux/Mac 獨(dú)立腳本
腳本不需要單獨(dú)的包含格式化的文本。
在可執(zhí)行路徑中,創(chuàng)建名為curltime的文件,粘貼下面內(nèi)容:
- #!/bin/bash
- curl -w @- -o /dev/null -s "$@" <<'EOF'
- time_namelookup: %{time_namelookup}\n
- time_connect: %{time_connect}\n
- time_appconnect: %{time_appconnect}\n
- time_pretransfer: %{time_pretransfer}\n
- time_redirect: %{time_redirect}\n
- time_starttransfer: %{time_starttransfer}\n
- ----------\n
- time_total: %{time_total}\n
- EOF
制作成windows快捷方式(bat批處理)
把下面的命令寫入curltime.bat:
curl -w "@%~dp0curl-format.txt" -o NUL -s %*
以上手段后,curltime wordpress.org就可以拿到cURL的請(qǐng)求耗時(shí)。
cURL還有一個(gè)小技巧:模擬連接/傳輸超時(shí)。
連接超時(shí)時(shí)間用--connect-timeout參數(shù)來指定,數(shù)據(jù)傳輸?shù)淖畲笤试S時(shí)間用-m參數(shù)來指定。
連接超時(shí)的話,出錯(cuò)提示形如:curl: (28) connect() timed out!
數(shù)據(jù)傳輸?shù)淖畲笤试S時(shí)間超時(shí)的話,出錯(cuò)提示形如:
curl: (28) Operation timed out after 2000 milliseconds with 0 bytes received