简体   繁体   English

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

[英]Using ctime to print current system time to millisecond precision?

I have a data acquisition program running in an Ubuntu environment.我有一个在 Ubuntu 环境中运行的数据采集程序。 When a data trigger is met, the program creates a new file containing the data, with the filename being a timestamp of when the trigger was met.当满足数据触发器时,程序会创建一个包含数据的新文件,文件名是满足触发器时的时间戳。 Right now I'm generating a timestamp using ctime and the program works:现在我正在使用 ctime 生成时间戳,并且程序可以工作:

#include <time.h>

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

A file is created named Fri_May_27_17_58_38_2022.txt创建了一个名为Fri_May_27_17_58_38_2022.txt的文件

Is it possible to use the same method to get a more precise timestamp to milliseconds?是否可以使用相同的方法来获得更精确的时间戳到毫秒?

On most platforms you can take the second part of a struct timespec ( tv_sec ) gotten from timespec_get and use localtime or gmtime to break it down into its components, leaving only the nano second part.在大多数平台上,您可以获取从timespec_getstruct timespec ( tv_sec ) 的第二部分,并使用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
    );
}

Possible output:可能的输出:

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

If you only need milliseconds:如果您只需要毫秒:

    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
    );

Possible output:可能的输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM