Linux中是否有shell命令以毫秒为单位获取时间?
当前回答
输出十进制秒数:
start=$(($(date +%s%N)/1000000)) \
&& sleep 2 \
&& end=$(($(date +%s%N)/1000000)) \
&& runtime=$((end - start))
divisor=1000 \
&& foo=$(printf "%s.%s" $(( runtime / divisor )) $(( runtime % divisor ))) \
&& printf "runtime %s\n" $foo # in bash integer cannot cast to float
输出:runtime 2.3
其他回答
纯bash解决方案
自bash 5.0(2019年1月7日发布)以来,您可以使用内置变量EPOCHREALTIME,它包含自epoch以来的秒数,包括小数点后精确到微秒(echo $EPOCHREALTIME输出类似1547624774.371210)。通过移除。最后三个地方是毫秒:
要么使用
(( t = ${EPOCHREALTIME/./} / 1000 ))
或者类似的东西
t=${EPOCHREALTIME/./} # remove the dot (s → µs)
t=${t%???} # remove the last three digits (µs → ms)
无论哪种方式t都是1547624774371。
我想从bash生成值,并在Java代码中使用该值转换回日期(Java .util)。
以下命令为我在bash文件中生成值:
日期+ % s000
输出十进制秒数:
start=$(($(date +%s%N)/1000000)) \
&& sleep 2 \
&& end=$(($(date +%s%N)/1000000)) \
&& runtime=$((end - start))
divisor=1000 \
&& foo=$(printf "%s.%s" $(( runtime / divisor )) $(( runtime % divisor ))) \
&& printf "runtime %s\n" $foo # in bash integer cannot cast to float
输出:runtime 2.3
日期+“% T。%N"返回当前时间,单位为纳秒。 06:46:41.431857000 日期+“% T。%6N”返回当前时间,其中纳秒四舍五入到前6位数字,即微秒。 06:47:07.183172 日期+“% T。%3N”返回当前时间,将纳秒四舍五入到前3位数字,即毫秒。 06:47:42.773
通常,date命令格式的每个字段都可以指定可选的字段宽度。
当你从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()以微秒精度返回时间。
推荐文章
- 如何解析unix时间戳到时间。时间
- 如何使用yyyyMMddHHmmss格式格式化当前时间?
- Shell脚本删除超过n天的目录
- 使用sudo时未找到命令
- SQL Developer只返回日期,而不是时间。我怎么解决这个问题?
- 如何防止rm报告文件未找到?
- 当有命令行参数时,如何使用GDB分析程序的核心转储文件?
- 如何检查shell脚本中是否存在命令?
- Bash:获取输出的第n列的最短方法
- 如何使用查找命令从列表中查找所有具有扩展名的文件?
- 如何获得一个变量值,如果变量名存储为字符串?
- RVM不是一个函数,用' RVM use…’不会起作用
- 如何强制从另一个SSH会话分离屏幕?
- 如何打破一个循环在Bash?
- 如何从终端机发送电子邮件?