C++ current system time in nanoseconds as long integer in order to send influxdb

Viewed 965

I need to get system time in nanoseconds and send it to influxdb as a timestamp. I know

std::chrono::high_resolution_clock::now()

gives current system time in nanosecodns but I could not manage to convert it to primitive types.

When I pass the code below, I see something like 1970-01-09T... in the database

std::chrono::high_resolution_clock::now().time_since_epoch().count()
2 Answers

You need to use std::chrono::system_clock instead of high_resolution_clock. Only system_clock reliably measures time since the 1970 epoch (which is what influxdb will be expecting).

Secondly, system_clock isn't guaranteed to measure time in units of nanoseconds, but you can correct for that.

Here is how to get your platforms best estimate of the number of nanoseconds since 1970-01-01 00:00:00 UTC (excluding leap seconds, which is normal and ok), and put it in a signed 64 bit integral type:

using namespace std::chrono;
long long t = time_point_cast<nanoseconds>(system_clock::now()).time_since_epoch().count();

now() returns you a time_point. You need to convert it to a duration in order to get the number of nanoseconds.

Probably what you are looking for is the time since the epoch, so you can do something like

std::chrono::nanoseconds ns = std::chrono::high_resolution_clock::now().time_since_epoch();
unsigned long result = ns.count();
Related