【问题标题】:Difference between `deadline_timer`and `waitable_timer` in `boost asio``boost asio`中`deadline_timer`和`waitable_timer`之间的区别
【发布时间】:2014-12-17 13:51:21
【问题描述】:

要在 5 秒内使计时器到期,
这两者之间有什么实际区别吗?
在这种情况下,任何一个(性能、资源等)比另一个更可取吗?

[选项1] deadline_timer

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

[选项 2]waitable_timersystem_timersteady_timer):

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

PS:请专注于比较deadline_timersystem_timer,而不是system_timersteady_timer

【问题讨论】:

    标签: c++ boost timer boost-asio


    【解决方案1】:

    唯一的区别在于使用的时钟类型。

    从 Boost 1.56 开始,basic_deadline_timerbasic_waitable_timer 在内部使用 detail::deadline_timer_service

    它执行等待的方式没有区别,唯一的区别在于它执行时间计算的方式。

    在其wait() 方法中,它使用Time_Traits::now() 来检查是否需要等待更多时间。对于system_timer,它是std::chrono::system_clock::now(),对于deadline_timer,它是boost::posix_time::microsec_clock::universal_time()boost::posix_time::second_clock::universal_time(),具体取决于是否存在高精度时钟(参见time_traits.hpp)。

    std::chrono::system_clock 实现由编译器/标准库供应商提供,而boost::posix_time::*clock 由 Boost 使用可用的系统函数实现。

    这些实现当然可能具有不同的性能和/或精度,具体取决于平台和编译器。

    【讨论】:

      【解决方案2】:

      这里对类似问题有很好的回应:https://stackoverflow.com/a/16364002/3491378

      基本上,主要区别在于,如果您预计系统时钟会发生任何外部变化,您应该使用 stable_timer——deadline_timer 延迟会受到这些变化的影响

      【讨论】:

      • 为了澄清你的答案,你的意思是在不修改系统时钟的情况下没有实际区别吗?
      • 如果我猜对了 - 是的。如果在您设置的延迟期间(示例中为 5 秒)未修改系统时钟,则实际差异可以忽略不计(正如 Anton 所说 - 唯一的区别在于它们的实现)
      猜你喜欢
      • 2021-11-22
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多