%20%E4%B8%AD%E7%94%9F%E6%88%90%E7%B2%BE%E7%A1%AE%E5%88%B0%E5%BE%AE%E7%A7%92%E7%9A%84%E6%97%B6%E9%97%B4%E6%88%B3.png)
我想在 unix shell 中生成具有微秒精度的文本时间戳,而不使用%N
date 选项(我正在使用 busybox,这是一个较小的 unix 工具集,没有此选项),作为我生成的输出的前缀。时间戳应具有以下格式"<seconds since epoc>.<microseconds>"
。
awk -f ./myawkscript.awk < /param | sed 's/$/\[<TIMESTAMP WOULD GO HERE>].'
因此期望的输出将是这样的:
[1305638345.123456] awk script output
我可以使用 轻松获取 epoc date +"%s"
,所以我的问题是,有没有办法从 shell 中获取微秒?
答案1
#include <stdio.h>
#include <sys/time.h>
int main() {
struct timeval t;
if (gettimeofday(&t, NULL) == 0)
printf("%d.%06u\n", t.tv_sec, t.tv_usec);
return 0;
}
使用以下方式编译cc -o timestamp timestamp.c
为了完整性:clock_gettime()
可以返回纳秒,但是使用awk
脚本无论如何都无法达到那个精度。