使用 ctime 以毫秒精度打印当前系统时间?

Using ctime to print current system time to millisecond precision?

我在 Ubuntu 环境中有一个数据采集程序 运行。当满足数据触发器时,程序会创建一个包含数据的新文件,文件名是满足触发器时的时间戳。现在我正在使用 ctime 生成时间戳并且程序运行:

#include <time.h>

time_t rawtime; // Generating time stamp
time(&rawtime);
sprintf(buffer, "/usb/%s.txt", ctime(&rawtime));

创建了一个名为 Fri_May_27_17_58_38_2022.txt

的文件

是否可以使用相同的方法得到更精确到毫秒的时间戳?

在大多数平台上,您可以使用从 timespec_get 获得的 struct timespec (tv_sec) 的 second 部分并使用 localtimegmtime 将其分解成它的组件,只留下纳秒部分。

#include <time.h>
#include <stdio.h>

int main() {
    struct timespec ts;
    timespec_get(&ts, TIME_UTC);
    time_t seconds = ts.tv_sec;

    printf("%s", ctime(&seconds)); // just for comparison

    struct tm *t = localtime(&seconds);

    printf("%04d-%02d-%02dT%02d:%02d:%02d.%09ld\n",
        t->tm_year+1900, t->tm_mon+1, t->tm_mday,
        t->tm_hour, t->tm_min, t->tm_sec,
        ts.tv_nsec
    );
}

可能的输出:

Fri May 27 18:36:14 2022
2022-05-27T18:36:14.513916611

如果只需要毫秒:

    printf("%04d-%02d-%02dT%02d:%02d:%02d.%03ld\n",
        t->tm_year+1900, t->tm_mon+1, t->tm_mday,
        t->tm_hour, t->tm_min, t->tm_sec,
        ts.tv_nsec / 1000000
    );

可能的输出:

Fri May 27 18:36:14 2022
2022-05-27T18:36:14.513