2014-02-16 63 views
2

執行時間假設我有三個劇本(a.sh b.sh c.sh)在腳本中推出了名爲launcher.sh:如何知道在linux

first=`date +%s` 

./a.sh & 
./b.sh & 
./c.sh & 

final=`date +%s` 

executionTime=`echo "scale=3;($final - $first)/3600" | bc` 

echo $executionTime 

我知道上面的腳本將不起作用,因爲啓動a.sh,b.sh和c.sh後,launcher.sh會立即結束。啓動a.sh,b.sh和c.sh而不使用「&」浪費時間,因爲它們不必等待對方。

假設他們的執行時間分別是5秒,10秒和7秒,我怎麼能得到10秒作爲整體執行時間?

回答

4

使用wait

first=`date +%s` 

./a.sh & 
./b.sh & 
./c.sh & 

wait 

... 

報價help wait

wait: wait [id]

Wait for job completion and return exit status. 

Waits for the process identified by ID, which may be a process ID or a 
job specification, and reports its termination status. If ID is not 
given, waits for all currently active child processes, and the return 
status is zero. If ID is a a job specification, waits for all processes 
in the job's pipeline. 

Exit Status: 
Returns the status of ID; fails if ID is invalid or an invalid option is 
given. 
+0

@Mat謝謝你教我一些新的關於降價。 (我想知道爲什麼變化沒有任何效果。) – devnull

+0

順便問一下,我可以要求更多?該手冊說等待當前活動的子進程,但有沒有可能子進程不活動?如果孩子的過程叫做睡眠,那是一個活躍的過程嗎? –

+1

如果它調用睡眠,它仍然被認爲是活動的。 –

2

的Linux自帶的timeÇ ommand是特別爲這種確切用法而設計的。只需撥打time yourscript即可。

當您的啓動程序腳本在後臺啓動進程時,僅有time是不夠的。正如@devnull所述,有一個wait命令阻止了一個調用,直到所有子進程終止。

有一個簡單的方法來等待和時間結合起來,而不需要修改你的啓動程序腳本而無需手動停止時間:應該做的伎倆

time `./launcher.sh;wait ` 

(只用一個簡單的例子就可以了,只要你在一個子shell中執行啓動器+等待(使用``),這就可以工作了(但是如果它輸出了某些東西,你就不會從啓動腳本中輸出))


最少例如:

test1.sh

./test2.sh & 

test2.sh

sleep 10 

結果:

$`時間./test1.sh; wait`

真正0m10.004s
用戶0m0.001s
SYS 0m0。001S

+0

@devnull erm ...必須同意這一點。我會編輯這個答案來反映,再加上提供一個方便的解決方案。 –

+0

我已經嘗試瞭解決方案@JohannesH。提到使用時間,它沒有工作。 –

+0

@MarcusThornton看我的編輯。它基本上是devnull建議的和我原來的解決方案的組合(所以也要相信他)。我測試了這個,它應該工作,並且是最簡單的方法去恕我直言。 –

0

就在退出腳本編寫

echo $SECONDS 

或運行在終端窗口腳本,類型

$> time your_script