Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mac OS X Shell Script Measure Time Elapsed

Tags:

shell

macos

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

like image 547
C. Porto Avatar asked Oct 20 '14 13:10

C. Porto


People also ask

How do I get elapsed time in bash?

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.

How do you calculate elapsed time in Unix?

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.

How does Shell determine time difference?

Nice and simple. If someone needs hours: echo "$(($diff / 3600)) hours, $((($diff / 60) % 60)) minutes and $(($diff % 60)) seconds elapsed."


2 Answers

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.

like image 126
Droppy Avatar answered Sep 27 '22 21:09

Droppy


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))
like image 34
Victor Dodon Avatar answered Sep 27 '22 22:09

Victor Dodon