Difference between `deadline_timer`and `waitable_timer` in `boost asio`

ALittleDiff picture ALittleDiff · Oct 22, 2014 · Viewed 9.5k times · Source

To expire a timer in 5 seconds,
is there any practical difference between these two?
Is any one preferable(performance, resource, etc.) to the other for this case?

[Option 1] deadline_timer:

boost::asio::deadline_timer timer(io_service);
timer.expires_from_now(boost::posix_time::seconds(5));

[Option 2] waitable_timer(system_timer or steady_timer):

boost::asio::system_timer timer(io_service);
timer.expires_from_now(std::chrono::seconds(5));

PS: Please concentrate on comparing deadline_timer vs. system_timer, rather than system_timer vs. steady_timer.

Answer

Anton Savin picture Anton Savin · Oct 22, 2014

The only difference is between clock types used.

As of Boost 1.56, both basic_deadline_timer and basic_waitable_timer use detail::deadline_timer_service inside.

There's no difference in how it performs waiting, the only difference is in how it performs time calculation.

In its wait() method it uses Time_Traits::now() to check if it needs to wait more. For system_timer it's std::chrono::system_clock::now(), and for deadline_timer it's boost::posix_time::microsec_clock::universal_time() or boost::posix_time::second_clock::universal_time() depending on the presence of high precision clock (see time_traits.hpp).

std::chrono::system_clock implementation is provided by a compiler/standard library vendor, whereas boost::posix_time::*clock is implemented by Boost using available system functions.

These implementations of course may have different performance and/or precision depending on the platform and the compiler.