How to get Bash execution time in milliseconds under Mac OS X?

Solution 1:

Since OSX is a BSD-ish system, it's strftime library doesn't have %N (http://www.freebsd.org/cgi/man.cgi?query=date)

Does the bash builtin time command give you information you need?

time some work here

Solution 2:

I would go this route if I needed milliseconds and BSD didn't support date +%s%N

perl -MTime::HiRes -e 'printf("%.0f\n",Time::HiRes::time()*1000)'

Solution 3:

If you install coreutils you can use the GNU Linux date by writing gdate.

coreutils is available with Homebrew : brew install coreutils.

Solution 4:

echo $(($(date +%s%N)/1000000))

This would convert from nano-seconds to milli-seconds.

From @mpy, date +%s.%N works.

Output is different between linux and OS X though:
linux: 1369322592.573787111
OS X: 1369322610.N

Solution 5:

As the other answer's mentioned, OS X's date doesn't support %N (nanoseconds).

Could you just save the commands to time as a script? Or use a subshell or command group for them:

time (sleep 0.1; echo a; sleep 0.1)
time { sleep 0.1; echo a; sleep 0.1; }

Or sum the times of individual commands:

$ time=$(TIMEFORMAT=%R; (time sleep 0.1; echo a) 2>&1 > /dev/null)
$ time+=+$(TIMEFORMAT=%R; (time sleep 0.1) 2>&1)
$ bc <<< $time
.206

Or use some scripting language:

$ ruby -e 'puts "%.3f" % Time.now'
1369329611.046
$ time ruby -e '""'
0.029
$ time ruby -e 'puts "%.3f" % Time.now'
1369329622.943
0.029

%.3f is a format specifier for a floating point number with 3 decimal points. Time.now is a class method of the Time class.