Mac OS X Shell Script Elapsed Measurement Time

How to measure elapsed time in milliseconds in a shell script in Mac OS X?

+3


source to share


2 answers


You can 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 built-in shells (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))

      

+4


source


Use the command time

( manpage ). It will be much cheaper than calling ruby

just to tell you the elapsed time:

$ time a_command

      

To "extract" time real

from a do (untested) command:



real_time=$(time a_command | grep ^real | awk 'print $2')

      

(where a_command

can be a shell function if needed)

This will return the value in minutes and seconds, so if you want the result in milliseconds, use python (or your favorite scripting language) to start the process with sync functions outside of the subprocess call and you won't be taking over scripting costs to get the current time. See this answer and this answer for more details .

+7


source







All Articles