How can I measure the time elapsed in milliseconds in a shell script in Mac OS X?
Asked
Active
Viewed 1.0k times
3 Answers
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.
-
how can I do that in the shell? I want to get 'real' specifically, can you elaborate? – C. Porto Oct 20 '14 at 13:53
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
-
1Thanks 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
-
1I 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