I like @Miata's answer because it draws attention to date +%s
solution. However, @Miata includes .%N
but I am not sure what benefit you will get looking at nanoseconds when there is the cost of executing the date
command in a subshell. So, in practice, date +%s
should be sufficient. The other thing to note is date +%s
epoch is 1970-01-01 00:00:00 UTC. Which means the time has an absolute epoch and you can share the time measurement between different instances of shell script or different machines.
(( start=$(date +%s) )) # 1604026743
# ... some activity that lasts for, say, 24 seconds
(( end=$(date -u +%s) )) # 1604026767
(( duration=end-start )) # 24
I like @glenn jackman's answer because it refers to SECONDS
bash built-in variable. The thing to note here is the epoch is the time when the process was started. So, we can only use this technique to measure times for things that happen within that script:
(( start=SECONDS )) # 10
# ... some activity that lasts for, say, 24 seconds
(( end=SECONDS )) # 34
(( duration=end-start )) # 24
Another thing is I put all my assignments within the (( ))
command. i.e. you can rewrite:
cmd=$(( some_expression ))
as
(( cmd=some_expression ))
By doing this, we can minimize the occurrence of the $
symbol.
/usr/bin/time your_script
...