Bash

在 bash 中獲取經過的時間

  • October 30, 2020

我想在腳本中的某一時刻執行以下操作:

start_time=date

在一個或多個程序執行之後:

end_time=date

然後這樣做:

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

我該怎麼做?

使用自紀元以來的時間輕鬆辨識腳本中的時間跨度

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 不支持浮點數,因此您需要使用像 bc 這樣的外部工具來比較時間,例如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

引用自:https://unix.stackexchange.com/questions/314365