用 CURL 獲得回應時間!



前言

  • curl 平常都單純用來測試連線,但有時候想計算回應時間,也可以支援!



說明

基本用法

根據 [1] 這篇,可以先新增一個 template 檔案,設定自己想看的回應時間格式:

1
vim curl-format.txt

貼上以下內容 (可以依據喜好調整變數)

1
2
3
4
5
6
7
8
     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
  time_starttransfer:  %{time_starttransfer}s\n
                     ----------\n
          time_total:  %{time_total}s\n

然後用 -w 參數指定 template 檔案,即可依照你指定的格式,顯示回應時間:

1
curl -w "@curl-format.txt" -o /dev/null -s "https://google.com/"

變數說明

  • -w "@curl-format.txt": tells cURL to use our format file
  • -o /dev/null: redirects the output of the request to /dev/null
  • -s tells cURL not to show a progress meter

包成函數

我喜歡將這個設定包成一個 function,方便重複使用、也不用新增或維護檔案。

最後就像這樣:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
curl_time() {
    curl -so /dev/null -w "\
   namelookup:  %{time_namelookup}s\n\
      connect:  %{time_connect}s\n\
   appconnect:  %{time_appconnect}s\n\
  pretransfer:  %{time_pretransfer}s\n\
     redirect:  %{time_redirect}s\n\
starttransfer:  %{time_starttransfer}s\n\
-------------------------\n\
        total:  %{time_total}s\n" "$@"
}

使用方式:

1
2
curl_time  "google.com"
curl_time  "ktlast.com"

結果

1
2
3
4
5
6
7
8
   namelookup:  0.164071s
      connect:  0.167617s
   appconnect:  0.000000s
  pretransfer:  0.167640s
     redirect:  0.000000s
starttransfer:  0.174057s
-------------------------
        total:  0.174125s

.bashrc

如果想要一直使用這個 function,可以將它加入 .bashrc,就不用每次都重複宣告:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# 開啟 .bashrc
vim ~/.bashrc

# 貼上以下內容
curl_time() {
    curl -so /dev/null -w "\
   namelookup:  %{time_namelookup}s\n\
      connect:  %{time_connect}s\n\
   appconnect:  %{time_appconnect}s\n\
  pretransfer:  %{time_pretransfer}s\n\
     redirect:  %{time_redirect}s\n\
starttransfer:  %{time_starttransfer}s\n\
-------------------------\n\
        total:  %{time_total}s\n" "$@"
}

重新登入一次,或是執行 source ~/.bashrc

就可以直接使用 curl_time 了!




REF

  1. https://stackoverflow.com/questions/18215389/how-do-i-measure-request-and-response-times-at-once-using-curl
Licensed under CC BY-NC-SA 4.0
最後更新 2024-05-16 02:51

主題 StackJimmy 設計