如何在 Linux 中為命令計時

如果你想成為一名優秀的 Linux 管理員,那麼你應該知道 time 命令。 它用於確定給定命令運行所需的時間。

它對於測試腳本和命令的性能很有用(即有助於查找 shell 腳本的執行時間或命令完成所需的時間)。

如何使用Linux時間命令

使用 time 命令,只需執行 time 使用您要作為輸入運行的命令/程序。 請檢查以下 example

$ time ping linoxide.com

output
PING linoxide.com (104.27.115.15) 56(84) bytes of data.
64 bytes from 104.27.115.15 (104.27.115.15): icmp_seq=1 ttl=58 time=1.77 ms
64 bytes from 104.27.115.15 (104.27.115.15): icmp_seq=2 ttl=58 time=2.12 ms
64 bytes from 104.27.115.15 (104.27.115.15): icmp_seq=3 ttl=58 time=1.65 ms

--- linoxide.com ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 10016ms
rtt min/avg/max/mdev = 1.118/1.476/2.124/0.362 ms

real 0m10.536s
user 0m0.002s
sys 0m0.007s

real 表示“ping”命令從執行到終止所用的掛鐘時間, usersys 所用的時間是 ping 用戶空間和內核空間。

如何使時間命令將其輸出寫入文件

要將 time 命令輸出寫入文件而不是打印輸出屏幕,請使用 -o 命令行選項,它需要一個文件名/路徑作為輸入。

$ /usr/bin/time -o /home/smart/time-output.txt ping linoxide.com

現在我們將在 stdout 上顯示 ping 的輸出,而 time 命令輸出將寫入文本文件。

筆記: 我們使用 /usr/bin/time 而不是 time 因為 shell 內置時間命令不提供 -o 選項。

如何將其輸出附加到現有文件

要將 time 命令輸出附加到現有文件而不是覆蓋它,請使用 -a 命令行選項。

$ /usr/bin/time -a /home/smart/time-output.txt ping linoxide.com

如何獲取linux時間命令的詳細輸出

我們可以使用 -v 用於生成詳細輸出的命令行選項。

$ time -v ping linoxide.com

output
Command being timed: "ping linoxide.com"
User time (seconds): 0.00
System time (seconds): 0.00
Percent of CPU this job got: 0%
Elapsed (wall clock) time (h:mm:ss or m:ss): 0:11.77
Average shared text size (kbytes): 0
Average unshared data size (kbytes): 0
Average stack size (kbytes): 0
Average total size (kbytes): 0
Maximum resident set size (kbytes): 3064
Average resident set size (kbytes): 0
Major (requiring I/O) page faults: 0
Minor (reclaiming a frame) page faults: 158
Voluntary context switches: 14
Involuntary context switches: 0
Swaps: 0
File system inputs: 0
File system outputs: 0
Socket messages sent: 0
Socket messages received: 0
Signals delivered: 0
Page size (bytes): 4096
Exit status: 0

如何自定義時間命令輸出

有大量的格式選項,如下表所示

C – 使用的名稱和命令行參數
D – 進程的非共享數據區的平均大小(以千字節為單位)
E – 時鐘格式的經過時間
F – 頁錯誤數
I – 進程輸入的文件系統數量
K – 進程的平均總內存使用量(以千字節為單位)
M – 最大駐留設置的進程在生命週期內的大小(以千字節為單位)
O – 進程輸出的文件系統數
P – 作業收到的 CPU 百分比
R – 次要或可恢復頁面錯誤的數量
S – 系統在內核模式下使用的 CPU 秒總數
U – 用戶模式使用的 CPU 秒總數
W – 進程被換出主內存的次數
X – 進程中共享文本的平均數量
Z – 以千字節為單位的系統頁面大小
c – 進程上下文切換的次數
e – 進程使用的實時時間(以秒為單位)
k – 傳遞給進程的信號數
p – 進程的平均非共享堆棧大小(以千字節為單位)
r – 進程接收的套接字消息數
s – 進程發送的套接字消息數
t – 進程的平均駐留集大小(以千字節為單位)
w – 進程自願切換上下文的次數
X – Exit 命令狀態

我們可以使用格式開關如下:

$ time -f "Elapsed Time = %E, Inputs %I, Outputs %O"

上述命令的輸出將是這樣的:

Elapsed Time = 0:01:00, Inputs 2, Outputs 1

如果我們想添加一個新行作為格式字符串的一部分,請使用換行符,如下所示:

$ time -f "Elapsed Time = %E n Inputs %I n Outputs %O"

Linux 時間命令版本

有三個時間命令版本,Bash、Zsh 和 Gnu 時間命令。 我們可以使用 type 命令來確定時間是二進制還是內置關鍵字。

$ type time

output
# Bash
time is a shell keyword

# Zsh
time is a reserved word

# GNU time (sh)
time is /usr/bin/time

請寫下您對時間命令的建議或意見,以獲取更多信息使用 時間手冊頁.