Reputation: 30645
I have a timestamp (nanoseconds since epoch):
uint64_t ts = .....;
and I'd like to check whether it is more than 5 seconds older than the current system time.
So I need to convert the timestamp to, a time_point
? and then subtract this from the current time (in nanoseconds), checking whether its value is greater than chrono::duration::seconds(5)
?
Got this so far:
const std::chrono::time_point tstp(std::chrono::duration_cast<std::chrono::nanoseconds>(rawNanos));
const std::chrono::time_point now = std::chrono::high_resolution_clock::now();
const bool old = now - tstp > std::chrono::seconds(5);
but struggling because of the constructor type for time_point.
Upvotes: 3
Views: 809
Reputation: 219345
You should not use high_resolution_clock
for this. On some platforms high_resolution_clock
counts time since the computer was booted up, not time since the Unix epoch.
Although not specified by the standard, the de facto standard is that on all platforms, system_clock
counts time since the Unix epoch.
I find it handy to first declare a templated type alias that is a time_point
based on system_clock
, templated on duration
. This makes it easy to create a time_point
of any precision that counts time since the Unix epoch:
template <class D>
using sys_time = std::chrono::time_point<std::chrono::system_clock, D>;
Given that:
uint64_t ts = 1235;
using namespace std::chrono;
const bool old = system_clock::now() >
sys_time<nanoseconds>{nanoseconds{ts}} + seconds{5};
In C++14 you'll be able to write:
const bool old = system_clock::now() >
sys_time<nanoseconds>{nanoseconds{ts}} + 5s;
Upvotes: 5