Millisecond time in a shell script

5,744

Solution 1

This will give you how many miliseconds have passed since the beginning of the Unix epoch :

date +%s%3N

You have to reduce the seconds*1000 which have passed until 00:00 AM today. Or you can just convert everything into miliseconds from this formula :

date +%H%M%S%3N

Like :

h=$(date +%H)
m=$(date +%M)
s=$(date +%S)
ms=$(date +%3N)
echo $((10#$h*3600000 + 10#$m*60000 + 10#$s*1000 + 10#$ms))

Executing this took me 4 miliseconds in average, you might want ot reduce that time.

Edit : If there is a leading zero in one of the variables the script will fail. I added 10# in front of the variable names, to strip the leading zeros, so that we get, for example, 8 instead of 08.

Solution 2

See if perl is portable enough:

perl -MTime::HiRes=time -MPOSIX=strftime -e '
    $now = int(time() * 1000);
    printf "%s.%03d\n", strftime("%H:%M:%S", localtime(int($now/1000))), ($now % 1000);
'

Time::HiRes and POSIX are both core Perl modules.

If you just want the epoch timestamp with fractional seconds:

$ perl -MTime::HiRes=time -le 'print time()'
1462218218.49011
Share:
5,744

Related videos on Youtube

RajuBhai
Author by

RajuBhai

Updated on September 18, 2022

Comments

  • RajuBhai
    RajuBhai almost 2 years

    How can someone print the entire time ie, for example 12:07:59:393(HH:MM:SS:milliseconds) in milliseconds. I found a lot of posts saying how to print Milliseconds along witht HHMMSS but I want to print the realtime clock in milliseconds. I'm using Linux.

    • schily
      schily about 8 years
      Are you interested in the entire wall clock run-time for programs started by the shell or are you interested in the time-of day-value with millisecond granularity?
    • RajuBhai
      RajuBhai about 8 years
      I am printing log packets and I need the timestamp to be in milliseconds when i print each line (wallclock precision) not time-of-day-value with millisecond granularity
  • schily
    schily about 8 years
    date +%s is non-portable and there is no portable way to retrieve more than second granularity from date.
  • Alessio
    Alessio about 8 years
    the question is tagged /linux. your anti-GNU prejudice is not applicable here.