0

I am trying to obtain the timestamp to the degree of microseconds in my program:

time_t t = time(NULL);
struct tm tm = *localtime(&t);
Buffer[Size-1] = 0;
char* BufferAsString = (char*)(Buffer+header_size);
if (strstr(BufferAsString,"Laptop Timestamp")){
    fprintf(timestampFile, "now: %d-%02d-%02d %02d:%02d:%02d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
    fprintf(timestampFile,BufferAsString);
    fprintf(timestampFile,"\n");
    fflush(timestampFile);
}

Currently this produces:

now: 2021-09-19 10:46:07

But I would like it to be

now: 2021-09-19 10:46:06.98164

I don't think tm is accurate to this degree according to this: https://www.cplusplus.com/reference/ctime/tm/

Is there another method of going about this?

I am using a raspberry pi 4 running the latest version of raspbian.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
Lyra Orwell
  • 1,048
  • 4
  • 17
  • 46
  • To get higher resolution of the time-stamp you need to use OS-specific functions, so please [edit] your question to include your target OS (as a tag). – Some programmer dude Sep 19 '21 at 10:40
  • @Someprogrammerdude Have done so now. – Lyra Orwell Sep 19 '21 at 10:45
  • https://stackoverflow.com/questions/361363/how-to-measure-time-in-milliseconds-using-ansi-c https://stackoverflow.com/questions/3673226/how-to-print-time-in-format-2009-08-10-181754-811 https://stackoverflow.com/questions/10192903/time-in-milliseconds-in-c https://stackoverflow.com/questions/3756323/how-to-get-the-current-time-in-milliseconds-from-c-in-linux/17083824 https://stackoverflow.com/questions/5833094/get-a-timestamp-in-c-in-microseconds/5833240#5833240 – KamilCuk Sep 19 '21 at 10:49
  • 1
    The old standard way to get high-resolution timestamps in Linux (or POSIX systems in general) used to be [`gettimeofday`](https://man7.org/linux/man-pages/man2/settimeofday.2.html). It's been obsoleted in favor of [`clock_gettime`](https://man7.org/linux/man-pages/man2/clock_gettime.2.html). – Some programmer dude Sep 19 '21 at 10:49
  • 1
    @Someprogrammerdude Not true that is OS-specific. C11 has [`timespec_get()`](https://en.cppreference.com/w/c/chrono/timespec_get), and [this StackOverflow answer](https://stackoverflow.com/questions/5833094/get-a-timestamp-in-c-in-microseconds/67731965#67731965) explains how to use it to get time in microseconds. – Luca Polito Sep 19 '21 at 10:51
  • @LucaPolito and he wrote clearly that its *standard in Linux*, quite a bit different from *standard in C*. – Kaihaku Sep 19 '21 at 10:58
  • @Kaihaku So like this: fprintf("now:%d\n",tv.tv_usec); – Lyra Orwell Sep 19 '21 at 11:11
  • That does not print anything to the file – Lyra Orwell Sep 19 '21 at 11:14

0 Answers0