内置printf可以打印当前时间(以毫秒或纳秒为单位) [英] Printing current time in milliseconds or nanoseconds with printf builtin

查看:1458
本文介绍了内置printf可以打印当前时间(以毫秒或纳秒为单位)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以使用内置的printf函数打印当前时间,而无需调用像date这样的外部命令,

We can print the current time with the builtin printf function, without needing to invoke an external command like date, like this:

printf '%(%Y-%m-%d:%H:%M:%S)T %s\n' -1
# sample output: 2019-03-30:17:39:36,846

我们如何使printf也可以打印毫秒或纳秒?在格式字符串中使用%3N%N无效:

How can we make printf to print milliseconds or nanoseconds as well? Using %3N or %N in the format string doesn't work:

printf '%(%Y-%m-%d:%H:%M:%S,%3N)T %s\n' -1 # outputs 2019-03-30:17:38:16,%3N
printf '%(%Y-%m-%d:%H:%M:%S,%N)T %s\n' -1  # outputs 2019-03-30:17:38:16,%N

但是,date命令可以正常工作:

However, the date command works fine:

date +%Y-%m-%d:%H:%M:%S,%3N # gives 2019-03-30:17:39:36,846
date +%Y-%m-%d:%H:%M:%S,%N  # gives 2019-03-30:17:39:36,160643077

这是在Red Hat Linux 7.3版上.

This is on a Red Hat Linux version 7.3.

推荐答案

bash 5中,您可以从EPOCHREALTIME获得微秒精度.但是,printf本身无法直接访问它,因此您需要自己提取微秒.

In bash 5, you can get microsecond precision from EPOCHREALTIME. However, printf itself has no way to access that directly, so you need to extract the microseconds yourself.

$ echo $EPOCHREALTIME; printf '%(%F:%T)T.%d\n' "$EPOCHSECONDS" "${EPOCHREALTIME#*.}"; echo $EPOCHREALTIME
1554006709.936990
2019-03-31:00:31:49.937048
1554006709.937083

这需要一些时间,但结果似乎准确到大约0.05毫秒.

This takes a little time, but the result appears to be accurate to about 0.05 milliseconds.

这篇关于内置printf可以打印当前时间(以毫秒或纳秒为单位)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆