Custom date and time including nanoseconds

1.5k views Asked by At

For this program I need to "grab the start time of the entire process within the max. time precision avail including nanoseconds." in the format:

April 9, 2022 13:18:17.123456789

I am able to get everything but the nanoseconds. Is it possible and/or what do you recommend?

Here is what I have:

//%B - Full Month Name
//%e - day space padded (%d 0 padded)
//$G - year (with century)
//%R - 24-hour HH:MM time, equivalent to %H:%M
//%N - nanoseconds?
//%T - ISO 8601 time format (HH:MM:SS), equivalent to %H:%M:%S

#define BUFFERSIZE 256

char timeStringEnd[BUFFERSIZE] = {0};

time_t timeEnd = time(NULL);

struct tm *timePointerEnd = localtime(&timeEnd);

strftime(timeStringEnd, BUFFERSIZE, "\n%B%e, %G %T", timePointerEnd);

puts(timeStringEnd);

%N doesn't want to work. Any supplemental material/sources on using timing is much appreciated . TIA

1

There are 1 answers

13
Jonathan Leffler On BEST ANSWER

The strftime() function doesn't support sub-second times. You'll need to add that yourself. You also need to use a function that returns sub-second times — that isn't time(). Assuming you have a POSIX-ish system, you can use clock_gettime():

struct timespec tv;
clock_gettime(CLOCK_REALTIME, &tv);
struct tm *timePointerEnd = localtime(&tv.tv_sec);
size_t nbytes = strftime(timeStringEnd, BUFFERSIZE, "\n%B%e, %G %T", timePointerEnd);
snprintf(timeStringEnd + nbytes, sizeof(timeStringEnd) - nbytes,
         "%.9ld", tv.tv_nsec);
puts(timeStringEnd);

Note that if you want to print microseconds, you use %.6ld and tm.tv_nsec / 1000; if you want to print milliseconds, you use %.3ld and tm.tv_nsec / 1000000. Care is required.

C11 provides the timespec_get() function that does roughly the same job. It uses a struct timespec, but the arguments are slightly different. You'd pass the pointer first and specify TIME_UTC as the second argument.

If you have neither of those functions available, the (old, obsolescent) POSIX function gettimeofday() provides microsecond resolution timing. And an even older function, ftime(), also from POSIX (but removed from the standard nearly two decades ago) provides millisecond resolution timing. Both of these are often available on non-POSIX systems. Windows has other functions too.