How can I measure the time elapsed in milliseconds in a shell script in Mac OS X?
The most common way to measure elapsed time in bash is to utilize the date command, which can show the current system date and time in a configurable format. Using the flexiblity of date 's display format, you can easily calculate elapsed time with different resolutions.
The Unix time number is zero at the Unix epoch and increases by exactly 86400 per day since the epoch. Thus 2004-09-16T00:00:00Z, 12677 days after the epoch, is represented by the Unix time number 12677 × 86400 = 1095292800.
Nice and simple. If someone needs hours: echo "$(($diff / 3600)) hours, $((($diff / 60) % 60)) minutes and $(($diff % 60)) seconds elapsed."
Use the time
command (manpage). This will be much cheaper than invoking ruby
just to tell you elapsed time:
$ time a_command
To "extract" the real
time from the command do (untested):
real_time=$(time a_command | grep ^real | awk 'print $2')
(where a_command
can be a shell function if necessary)
This will return the value in minutes and seconds, so if you want the result in milliseconds then use python (or your favourite scripting language) to run the process with timing functions around the outside of the sub-process invocation and you will not incur the cost invoking the scripting language just to get the current time. See this answer and this answer for details.
You may use:
start_ms=$(ruby -e 'puts (Time.now.to_f * 1000).to_i')
# do some work
end_ms=$(ruby -e 'puts (Time.now.to_f * 1000).to_i')
elapsed_ms=$((end_ms - start_ms))
echo "$elapsed_ms ms passed"
OR only shell builtins (works in bash and zsh):
start_ns=$(date +%s%N)
# do some work
end_ns=$(date +%s%N)
elapsed_ms=$(((end_ns - start_ns) / 1000000))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With