mercredi 22 juillet 2015

How to convert std::chrono::time_point to uint64_t?

I am trying to see whether my data is 120 second (or 2 minutes) old or not by looking at the timestamp of the data so I have below code as I am using chrono package in C++:

uint64_t now = duration_cast<milliseconds>(steady_clock::now().time_since_epoch()).count();
// check for 2 minutes old data
bool is_old = (120 * 1000 < (now - data_holder->getTimestamp()));   

uint64_t value = now;
while (now < data_holder->getTimestamp() + 80 * 1000 
        && now < value + 80 * 1000) {
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    now = duration_cast<milliseconds>(steady_clock::now().time_since_epoch()).count();
}

In the above code data_holder->getTimestamp() is uint64_t which returns timestamp in milliseconds.

Now when I print out now variable value, I see this 10011360 and when I print out data_holder->getTimestamp() value which is 1437520382241

2015-07-21 16:13:02,530 WARN 0x7f35312d1700 data_check - now value: 10011360 , data holder timestamp: 1437520382241

And from the above data holder timestamp, it doesn't look to be 120 second old data right so I feel something is wrong in my code? Since if I convert that data holder timestamp to actual time (using epoch converter) and then compare it with logs time as shown above it is almost same.

So I decided to use system_clock instead of steady_clock and came up with below code in which I started to use auto instead of uint64_t.

auto now = system_clock::now();
auto dh_ts = system_clock::time_point{milliseconds{data_holder->getTimestamp()}};
bool is_old = (minutes{2} < (now - dh_ts));

Earlier, I was using now variable value as uint64_t instead of auto. Now after the above code, I have something like this in my original code since now is not uint64_t so I am getting compilation error while compiling the code.

uint64_t value = now;
while (now < data_holder->getTimestamp() + 80 * 1000 
        && now < value + 80 * 1000) {
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    now = duration_cast<milliseconds>(steady_clock::now().time_since_epoch()).count();
}

What is the right way to fix this? I cannot change data_holder->getTimestamp() data type, it has to be uint64_t since other code is also using it.

Here is the error:

error: cannot convert std::chrono::time_point<std::chrono::_V2::system_clock, std::chrono::duration<long int, std::ratio<1l, 1000000000l> > >â to âuint64_t {aka long unsigned int}â in initialization

Aucun commentaire:

Enregistrer un commentaire