In Linux I can find the current time in milliseconds using the command:
date +%s%N
but on FreeBSD I get only
[13:38 ]#date +%s%N
1299148740N
How can I get the time in milliseconds (or nanoseconds) in FreeBSD?
In Linux I can find the current time in milliseconds using the command:
date +%s%N
but on FreeBSD I get only
[13:38 ]#date +%s%N
1299148740N
How can I get the time in milliseconds (or nanoseconds) in FreeBSD?
Use gettimeofday()
, for example:
#include <stdio.h>
#include <sys/time.h>
int main(void)
{
struct timeval time_now;
gettimeofday(&time_now,NULL);
printf ("%ld secs, %ld usecs\n",time_now.tv_sec,time_now.tv_usec);
return 0;
}
The BSD date
command doesn't support milliseconds. If you want a date
with millisecond support, install the GNU coreutils
package.
I encountered this on OS X, whose date
comes from BSD. The solution was to brew install coreutils
and ln -sf /usr/local/bin/gdate $HOME/bin
, and making sure that $HOME/bin
comes first in PATH
.
Try using tai64n
from daemontools
:
$ echo | tai64n | tai64nlocal
2011-03-03 09:45:37.833010500
$ ps | tai64n | tai64nlocal
2011-03-03 09:52:30.817146500 PID TTY TIME CMD
2011-03-03 09:52:30.817150500 7154 pts/1 00:00:07 bash
2011-03-03 09:52:30.817157500 20099 pts/1 00:00:00 ps
2011-03-03 09:52:30.817159500 20100 pts/1 00:00:00 tai64n
2011-03-03 09:52:30.817162500 20101 pts/1 00:00:00 tai64nlocal
Here's a one-liner for any recent Perl:
perl -MTime::HiRes=gettimeofday -MPOSIX=strftime -e '($s,$us) = gettimeofday(); printf "%d.%06d\n", $s, $us'
1487594425.611120
(modified from this answer to a similar question)
Another way to get milliseconds is to use Python:
time_ms=$( python3 -c'import time; print(time.time())' )
echo $time_ms
Outputs:
1570807434.2774572
Note that python 2.x only returns 100ths of a second. May need to be tweaked slightly if your OS is using only Python 2.x to get more granularity.