Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nanoseconds since midnight

Tags:

c

linux

time

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?

like image 288
user997112 Avatar asked Dec 03 '25 18:12

user997112


1 Answers

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);
like image 106
dbush Avatar answered Dec 06 '25 07:12

dbush