Linux中是否有shell命令以毫秒为单位获取时间?
当前回答
date命令在OS X上没有提供毫秒,所以使用了python中的别名
millis(){ python -c "import time; print(int(time.time()*1000))"; }
OR
alias millis='python -c "import time; print(int(time.time()*1000))"'
编辑:跟随@CharlesDuffy的评论。 fork任何子进程都需要额外的时间。
$ time date +%s%N
1597103627N
date +%s%N 0.00s user 0.00s system 63% cpu 0.006 total
Python仍然在改进它的虚拟机启动时间,它没有提前编译的代码(比如日期)快。
在我的机器上,它花了大约30 - 60毫秒(即日期花费的6毫秒的5 -10倍)
$ time python -c "import time; print(int(time.time()*1000))"
1597103899460
python -c "import time; print(int(time.time()*1000))" 0.03s user 0.01s system 83% cpu 0.053 total
我认为awk比python轻量级,所以awk的范围是6ms到12ms(即日期的1x到2x):
$ time awk '@load "time"; BEGIN{print int(1000 * gettimeofday())}'
1597103729525
awk '@load "time"; BEGIN{print int(1000 * gettimeofday())}' 0.00s user 0.00s system 74% cpu 0.010 total
其他回答
date +%s%N返回秒数+当前纳秒。
因此,echo $(($(date +%s%N)/1000000))就是您所需要的。
例子:
$ echo $(($(date +%s%N)/1000000))
1535546718115
Date +%s返回自epoch以来的秒数,如果有用的话。
用时间和时区显示日期
日期+"%d-%m-%Y %T "。% N % Z”
输出22
下面是一个在Linux上以毫秒为单位获取时间的便携式hack:
#!/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
输出结果为:
3010
这是一个非常廉价的操作,它与shell内部程序和procfs一起工作。
当你从4.1版本开始使用GNU AWK时,你可以加载时间库并执行以下操作:
$ awk '@load "time"; BEGIN{printf "%.6f", gettimeofday()}'
这将以秒为单位打印自1970-01-01T00:00:00以来的当前时间,精度为亚秒。
the_time = gettimeofday() Return the time in seconds that has elapsed since 1970-01-01 UTC as a floating-point value. If the time is unavailable on this platform, return -1 and set ERRNO. The returned time should have sub-second precision, but the actual precision may vary based on the platform. If the standard C gettimeofday() system call is available on this platform, then it simply returns the value. Otherwise, if on MS-Windows, it tries to use GetSystemTimeAsFileTime(). source: GNU awk manual
在Linux系统上,标准C函数getimeofday()以微秒精度返回时间。
date命令在OS X上没有提供毫秒,所以使用了python中的别名
millis(){ python -c "import time; print(int(time.time()*1000))"; }
OR
alias millis='python -c "import time; print(int(time.time()*1000))"'
编辑:跟随@CharlesDuffy的评论。 fork任何子进程都需要额外的时间。
$ time date +%s%N
1597103627N
date +%s%N 0.00s user 0.00s system 63% cpu 0.006 total
Python仍然在改进它的虚拟机启动时间,它没有提前编译的代码(比如日期)快。
在我的机器上,它花了大约30 - 60毫秒(即日期花费的6毫秒的5 -10倍)
$ time python -c "import time; print(int(time.time()*1000))"
1597103899460
python -c "import time; print(int(time.time()*1000))" 0.03s user 0.01s system 83% cpu 0.053 total
我认为awk比python轻量级,所以awk的范围是6ms到12ms(即日期的1x到2x):
$ time awk '@load "time"; BEGIN{print int(1000 * gettimeofday())}'
1597103729525
awk '@load "time"; BEGIN{print int(1000 * gettimeofday())}' 0.00s user 0.00s system 74% cpu 0.010 total