I have following C code:
uint64_t combine(uint32_t const sec, uint32_t const usec){
return (uint64_t) sec << 32 | usec;
};
uint64_t now3(){
struct timeval tv;
gettimeofday(&tv, NULL);
return combine((uint32_t) tv.tv_sec, (uint32_t) tv.tv_usec);
}
What this do it combine 32 bit timestamp, and 32 bit "something", probably micro/nanoseconds into single 64 bit integer.
I have really hard time to rewrite it with C++11 chrono.
This is what I did so far, but I think this is wrong way to do it.
auto tse = std::chrono::system_clock::now().time_since_epoch();
auto dur = std::chrono::duration_cast<std::chrono::nanoseconds>( tse ).count();
uint64_t time = static_cast<uint64_t>( dur );
Important note - I only care about first 32 bit to be "valid" timestamp.
Second 32 bit "part" can be anything - nano or microseconds - everything is good as long as two sequential calls of this function give me different second "part".
The C++11 chrono types use only one number to represent a time since a given Epoch, unlike the
timeval
(ortimespec
) structure which uses two numbers to precisely represent a time. So with C++11 chrono you don't need thecombine()
method.The content of the timestamp returned by
now()
depends on the clock you use; there are tree clocks, described in http://en.cppreference.com/w/cpp/chrono :If you want successive timestamps to be always different, use the steady clock:
Edit: answer to comment
Output:
Here is code to do that:
This just output for me: