内置printf可以打印当前时间(以毫秒或纳秒为单位)

编程入门 行业动态 更新时间:2024-10-28 12:25:21
本文介绍了内置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可以打印当前时间(以毫秒或纳秒为单位)

本文发布于:2023-10-08 13:45:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1472806.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:单位   时间   printf

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!