5

How can I measure the time elapsed in milliseconds in a shell script in Mac OS X?

C. Porto
  • 631
  • 3
  • 12
  • 26
  • possible duplicate of [Using time command in bash script](http://stackoverflow.com/questions/3683434/using-time-command-in-bash-script) – Paul R Oct 20 '14 at 13:18

3 Answers3

15

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.

Community
  • 1
  • 1
Droppy
  • 9,691
  • 1
  • 20
  • 27
3

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))
Eugene Petrenko
  • 4,874
  • 27
  • 36
Victor Dodon
  • 1,796
  • 3
  • 18
  • 27
  • 1
    Thanks for that, I will be using the ruby approach because since I'm operating with Mac OS X the second approach doesn't actually work, but I'm curious if there is a way to measure milliseconds natively. – C. Porto Oct 20 '14 at 13:29
  • 1
    I have updated my answer, you can the second approach for a shell-only method of measuring an interval. – Victor Dodon Oct 20 '14 at 13:33
0

to calculate code execution inside your main shell script

START=$(date +%s) 

//you script like flutter build ipa

END=$(date +%s)
DIFF=$(echo "$END - $START" | bc)
echo "whole process finished in $DIFF seconds"
Fuad All
  • 871
  • 11
  • 13