在Linux中,我可以使用以下命令找到当前时间(以毫秒为单位):
date +%s%N
但是在FreeBSD上我只得到
[13:38 ]#date +%s%N
1299148740N
如何在FreeBSD中以毫秒(或纳秒)的速度获取时间?
答案 0 :(得分:6)
BSD date
命令不支持毫秒。如果您希望date
支持毫秒级,请安装GNU coreutils
包。
我在OS X上遇到过这种情况,其date
来自BSD。解决方案是brew install coreutils
和ln -sf /usr/local/bin/gdate $HOME/bin
,并确保$HOME/bin
位于PATH
的第一位。
答案 1 :(得分:3)
使用gettimeofday()
,例如:
#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;
}
答案 2 :(得分:1)
尝试使用tai64n
中的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
答案 3 :(得分:0)
这是最新Perl的单行代码:
perl -MTime::HiRes=gettimeofday -MPOSIX=strftime -e '($s,$us) = gettimeofday(); printf "%d.%06d\n", $s, $us'
1487594425.611120
(从this answer修改为类似问题)
答案 4 :(得分:0)
获取毫秒数的另一种方法是使用Python:
time_ms=$( python3 -c'import time; print(time.time())' )
echo $time_ms
输出:
1570807434.2774572
请注意,python 2.x仅返回百分之一秒。如果您的操作系统仅使用Python 2.x,则可能需要稍作调整。