如何知道 Linux 中的执行时间



>假设我有三个脚本(a.sh b.sh c.sh)要在名为 launcher.sh 的脚本中启动:

first=`date +%s`
./a.sh &
./b.sh &
./c.sh &
final=`date +%s`
executionTime=`echo "scale=3;($final - $first)/3600" | bc`
echo $executionTime

我知道上面的脚本不起作用,因为 launcher.sh 启动 a.sh、b.sh 和 c.sh 后会立即完成。在没有"&"的情况下启动 a.sh、b.sh 和 c.sh 是在浪费时间,因为它们不必互相等待。

假设它们的执行时间分别为 5 秒、10 秒

和 7 秒,我怎样才能得到 10 秒作为整体执行时间?

使用 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.

linux附带了专门为此确切用法设计的time命令。只需致电time yourscript.

当您的启动器脚本在后台启动进程时,仅靠time是不够的。如@devnull所述,有一个wait命令阻止调用,直到所有子进程都终止。

有一种简单的方法可以将等待和时间结合起来,而无需修改启动器脚本,也无需手动停止时间:

time `./launcher.sh;wait `

应该做这个伎俩。

(用一个最小的例子尝试过这个。 只要你在子壳中执行启动器 + 等待(使用 ''),这将起作用(但如果它确实输出了一些东西,你会从 launcerh 脚本中丢失 otuput))


最小示例:

test1.sh

./test2.sh &

test2.sh

sleep 10

结果:

$ time './test1.sh;wait'

真实 0M10.004秒
用户 0M0.001s
系统 0m0.001s

在退出脚本之前写入

echo $SECONDS

或者要在终端窗口中运行脚本,请键入

$> time your_script

最新更新