I have a timestamp representing nanoseconds since midnight. I would like to calculate the number of nanoseconds (right now) since midnight, to subtract the two timestamps and measure the latency. I would like to do this using the fastest operations.
The target platform is x86-64 Linux, Clang compiler, no old Kernel or hardware, I don't care about daylight saving, there are no round cases to cover etc.
I understand:
struct timespec now;
clock_gettime(CLOCK_REALTIME, &now);
will return the number of seconds since Epoch and the number of nanoseconds after the last second.
I therefore think I just need to create a time point representing midnight, extract the number of seconds since Epoch from midnight and then do:
now_nanos = (((now.seconds_since_epoch) - (midnight.seconds_since_epoch)) x 1 billion) + now.nanos_since_last_second
How do I create a time point representing midnight, to extract the number of seconds since Epoch?
I have seen examples using mktime() returning a time_t but I wasn't sure how to extract the seconds since Epoch?
First get the current time with time. Then pass the result of that to localtime_r to get the time broken up into its components pieces. Zero out the hours, miniutes, and seconds, then use mktime to switch back to seconds since the epoch.
time_t now = time(NULL);
struct tm tm;
localtime_r(&now, &tm);
tm.tm_sec = 0;
tm.tm_min = 0;
tm.tm_hour = 0;
time_t start_of_day = mktime(&tm);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With