Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast `std::chrono::milliseconds` to `boost::posix_time::milliseconds`

I am using a boost::asio::deadline_timer like so to set some timeout before an async_read operation on a tcp socket. I am using boost 1.61.

long time_out_millis = 2000;
boost::asio::deadline_timer theTimer(theSocket.get_io_service(), boost::posix_time::milliseconds(time_out_millis));

Problem:
Other parts of my code use std::chrono::milliseconds. I want use std::chrono instead of the "long time_out_millis" & if possible use std::chrono::milliseconds instead of boost::posix_time::milliseconds. How can I do that?

Question:
So, how can I use std::chrono::milliseconds here ? Is there a way I cast from std::chrono::milliseconds to boost::posix_time::milliseconds ?

like image 806
TheWaterProgrammer Avatar asked Mar 08 '23 11:03

TheWaterProgrammer


1 Answers

Direct solution: duration_cast<>:

using namespace std::chrono;
using namespace std::chrono_literals; 

boost::posix_time::seconds(duration_cast<seconds>(2s).count());

Still not nice. But this is your key.

BETTER NEWS

In any c++11 or higher scenario, simply

#include <boost/asio/high_resolution_timer.hpp>

And enjoy a timer completely parameterized on std::chrono from bottom to top. No more impedance mismatch:

Live On Coliru

#include <boost/asio/high_resolution_timer.hpp>
using namespace std::chrono_literals;

int main() {
    boost::asio::io_service svc;

    boost::asio::high_resolution_timer tim(svc);

    tim.expires_from_now(1s);
    tim.expires_from_now(100ms);
    tim.expires_from_now(3h);
    tim.expires_from_now(15'000us);
    tim.expires_from_now(15'000'000ns);
}

Note this would change your

long time_out_millis = 2000;

Into something like

Clock::duration timeout = 2000ms;
like image 120
sehe Avatar answered Apr 06 '23 09:04

sehe