Coder Perfect

Get time in milliseconds with this command.

Problem

Is there a shell command in Linux to get the time in milliseconds?

Asked by MOHAMED

Solution #1

Every field of the date command’s format can have an optional field width in general.

Answered by Michael Defort

Solution #2

The amount of seconds + current nanoseconds is returned by date + percent s percent N.

As a result, echo $((date + percent s percent N)/1000000)) will suffice.

Example:

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

If it’s beneficial, date + percent s returns the amount of seconds since the epoch.

Answered by Alper

Solution #3

Nano has a value of 109 while milli has a value of 103. As a result, we can convert nanoseconds to milliseconds using the first three characters:

date +%s%3N

From man date:

Server Fault’s website is the source of this information. In Bash, how can I retrieve the current Unix time in milliseconds?

Answered by fedorqui ‘SO stop harming’

Solution #4

I propose installing coreutils using Homebrew on OS X if date does not support the percent N flag. This will provide you access to gdate, a command that works similarly to date on Linux platforms.

brew install coreutils

You can always add this to your.bash aliases for a more “natural” experience:

alias date='gdate'

Then execute

$ date +%s%N

Answered by Joshua Cook

Solution #5

Here’s a workaround for getting time in milliseconds on Linux that’s somewhat portable:

#!/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 low-cost operation that uses shell internals and procfs.

Answered by Bastian Bittorf

Post is based on https://stackoverflow.com/questions/16548528/command-to-get-time-in-milliseconds