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()
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();