Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using ctime to print current system time to millisecond precision?

I have a data acquisition program running in an Ubuntu environment. 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:

#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

Is it possible to use the same method to get a more precise timestamp to milliseconds?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

#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 % 1000
    );

Possible output:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading