下面轉載的文章詳細地介紹了time出來顯示的“real”“user”“sys”的真正含義。
Linux中time命令,我們經常用來計算某個程序的運行耗時,用戶態cpu耗時,系統態cpu耗時。
例如:
-
$ time foo
-
real 0m0.003s
-
user 0m0.000s
-
sys 0m0.004s$
那么這三個時間都具體代表什么意思呢?
[1] real : 表示foo程序整個的運行耗時,可以理解為foo運行開始時刻你看了一下手表,foo運行結束時,你又看了一下手表,兩次時間的差值就是本次real 代表的值
舉個極端的例子如下:可以看到real time恰好為2秒。
# time sleep 2
real 0m2.003s
user 0m0.000ssys 0m0.000s
[2] user 0m0.000s:這個時間代表的是foo運行在用戶態的cpu時間,什么意思?
首先,我來講一下用戶態和核心態:
核心態(Kernel Mode):
在內核態,代碼擁有完全的,不受任何限制的訪問底層硬件的能力。可以執行任意的CPU指令,訪問任意的內存地址。內核態通常情況下,都是為那些最底層的,由操作系統提供的,可信可靠的代碼來運行的。內核態的代碼崩潰將是災難性的,它會影響到整個系統。
—– In Kernel mode, the executing code has complete and unrestricted access to the underlying hardware. It can execute any CPU instruction and reference any memory address. Kernel mode is generally reserved for the lowest-level, most trusted functions of the operating system. Crashes in kernel mode are catastrophic; they will halt the entire PC.
用戶態(User Mode):
在用戶態,代碼不具備直接訪問硬件或者訪問內存的能力,而必須借助操作系統提供的可靠的,底層的APIs來訪問硬件或者內存。由於這種隔離帶來的保護作用,用戶態的代碼崩潰(Crash),系統是可以恢復的。我們大多數的代碼都是運行在用戶態的。
—– In User mode, the executing code has no ability to directly access hardware or reference memory. Code running in user mode must delegate to system APIs to access hardware or memory. Due to the protection afforded by this sort of isolation, crashes in user mode are always recoverable. Most of the code running on your computer will execute in user mode.
為什么要區分Kernel Mode 和 User Mode:
隔離保護,使得系統更穩定。
好,講完用戶態和核心態之后,我們來看user time,說過了,這個指的是程序foo運行在用戶態的cpu時間,cpu時間不是牆上的鍾走過的時間,而是指CPU工作時間。
[3] sys 0m0.004s : 這個時間代表的是foo運行在核心態的cpu時間。
好,講完上面的這些,我們來看看這三個的關系,這三者之間沒有嚴格的關系,常見的誤區有:
誤區一: real_time = user_time + sys_time
我們錯誤的理解為,real time 就等於 user time + sys time,這是不對的,real time是時鍾走過的時間,user time 是程序在用戶態的cpu時間,sys time 為程序在核心態的cpu時間。
利用這三者,我們可以計算程序運行期間的cpu利用率如下:
%cpu_usage = (user_time + sys_time)/real_time * 100%
如:
# time sleep 2
real 0m2.003s
user 0m0.000ssys 0m0.000s
cpu利用率為0,因為本身就是這樣的,sleep 了2秒,時鍾走過了2秒,但是cpu時間都為0,所以利用率為0
誤區二:real_time > user_time + sys_time
一般來說,上面是成立的,上面的情況在單cpu的情況下,往往都是對的。
但是在多核cpu情況下,而且代碼寫的確實很漂亮,能把多核cpu都利用起來,那么這時候上面的關系就不成立了,例如可能出現下面的情況,請不要驚奇。
real 1m47.363s
user 2m41.318ssys 0m4.013s
誤區三:real_time < user_time + sys_time
一般來講不會有人闖入這個誤區^^