Bash – Get Elapsed Time

bashdatetime

I would like to do the following at one point in a script:

start_time=date

and this after a process or processes have run:

end_time=date

and then do this:

elapsed=$end_time-$start_time
echo "Total of $elapsed seconds elapsed for process"

How would I do this?

Best Answer

Use the time since epoch to easily identify a span of time in a script

man date
%s     seconds since 1970-01-01 00:00:00 UTC
%N     nanoseconds (000000000..999999999)

.

start_time="$(date -u +%s)"
sleep 5
end_time="$(date -u +%s)"

elapsed="$(($end_time-$start_time))"
echo "Total of $elapsed seconds elapsed for process"

 Total of 5 seconds elapsed for process

Bash doesn't support floating point numbers, so you'll need to use a external tool like bc to compare times like 1475705058.042270582-1475705053.040524971

start_time="$(date -u +%s.%N)"
sleep 5
end_time="$(date -u +%s.%N)"

elapsed="$(bc <<<"$end_time-$start_time")"
echo "Total of $elapsed seconds elapsed for process"

 Total of 5.001884264 seconds elapsed for process