Command to get time in milliseconds
Solution 1:
-
date +"%T.%N"
returns the current time with nanoseconds.06:46:41.431857000
-
date +"%T.%6N"
returns the current time with nanoseconds rounded to the first 6 digits, which is microseconds.06:47:07.183172
-
date +"%T.%3N"
returns the current time with nanoseconds rounded to the first 3 digits, which is milliseconds.06:47:42.773
In general, every field of the date
command's format can be given an optional field width.
Solution 2:
date +%s%N
returns the number of seconds + current nanoseconds.
Therefore, echo $(($(date +%s%N)/1000000))
is what you need.
Example:
$ echo $(($(date +%s%N)/1000000))
1535546718115
date +%s
returns the number of seconds since the epoch, if that's useful.
Solution 3:
Nano is 10−9 and milli 10−3. Hence, we can use the three first characters of nanoseconds to get the milliseconds:
date +%s%3N
From man date
:
%N nanoseconds (000000000..999999999)
%s seconds since 1970-01-01 00:00:00 UTC
Source: Server Fault's How do I get the current Unix time in milliseconds in Bash?.
Solution 4:
On OS X, where date
does not support the %N
flag, I recommend installing coreutils
using Homebrew. This will give you access to a command called gdate
that will behave as date
does on Linux systems.
brew install coreutils
For a more "native" experience, you can always add this to your .bash_aliases
:
alias date='gdate'
Then execute
$ date +%s%N
Solution 5:
Here is a somehow portable hack for Linux for getting time in milliseconds:
#!/bin/sh
read up rest </proc/uptime; t1="${up%.*}${up#*.}"
sleep 3 # your command
read up rest </proc/uptime; t2="${up%.*}${up#*.}"
millisec=$(( 10*(t2-t1) ))
echo $millisec
The output is:
3010
This is a very cheap operation, which works with shell internals and procfs.