How to know the execution time in linux

2019-07-15 12:52发布

问题:

Suppose that I have three script(a.sh b.sh c.sh) to be launched in a script called launcher.sh:

first=`date +%s`

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

final=`date +%s`

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

echo $executionTime

I know above script won't work because launcher.sh will finish immediately after launching a.sh, b.sh and c.sh. Launching a.sh, b.sh and c.sh without "&" is wasting time because they don't have to wait for each other.

Suppose that the execution time for them are 5 seconds, 10 seconds and 7 second respectively, how can I get 10 seconds as the overall execution time?

回答1:

Use wait:

first=`date +%s`

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

wait

...

Quoting 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.


回答2:

linux comes with the time command that is especiall designed for this exact usage. Just call time yourscript.

As your launcher script starts processes in the background, time alone isn't sufficient. As stated by @devnull, there is the wait command that blocks a call until all subprocesses have terminated.

There is an easy way to combine wait and time, without modifying your launcher script and without the need to manually stop the time:

time `./launcher.sh;wait `

should do the trick.

(tried this with a minimal example. as long as you execute the launcher + wait inside a subshell (using ``), this will work (but you loose otuput from the launcerh script if it does output something))


Minimal example:

test1.sh

./test2.sh &

test2.sh

sleep 10

Result:

$ time `./test1.sh;wait`

real 0m10.004s
user 0m0.001s
sys 0m0.001s



回答3:

Just before exit your script write

echo $SECONDS

or to run your script in a terminal windows, type

$> time your_script