【问题标题】:how to get custom (chrono) timer work with sleep_until?如何让自定义(计时)计时器与 sleep_until 一起工作?
【发布时间】:2014-03-26 20:13:27
【问题描述】:

我有一个自定义计时器模板,我想在std::this_thread::sleep_until() 中使用它。所以我的now() 方法看起来像这样:

static time_point now() {
    return time_point(timer_T::now() - epoch_);
}

其中 epoch_timer_T::now() 初始化。现在我希望能够 sleep_until 一个特定的时间点。

    std::this_thread::sleep_until(my_timer<>::now() + std::chrono::seconds(1));

我认为我的问题是我必须将 time_point 与 my_timer 作为(模板)Clock 参数,但现在不同的时间点之间存在转换。类似:

 using time_point = std::chrono::time_point<my_timer<timer_T>>;

代码可以在here找到。

我怎样才能让它发挥作用?另外,是否有一个小的 chrono howto out,我可以在其中找到一些如何创建自定义计时器的信息?

【问题讨论】:

  • 您正在更改 time_point 的含义,根据定义,它必须存储自纪元以来的持续时间。如果您不遵守规则,则依赖于该规则的 API 将无法工作。创建您自己的完全不同的时间点类,隐式转换为实时时间点。
  • 是的,但是标准中没有定义时代,所以我认为应该创建一个自己的时钟,因为 time_point 是基于您作为模板参数提供的时钟。
  • 是的,创建自己的时钟是可以的,它可以使用它需要的任何时代。 “纪元”并不意味着“1970 年第一天的午夜”;这就是“UNIX 时代”。 “纪元”的意思很简单,就是“参考日期”。

标签: c++ c++11 chrono


【解决方案1】:

通过查看 sleep_until,它使用 time_point 的时钟模板参数来查询当前时间。因此,这是在代码中定义时间点的正确方法:

#include <chrono>
#include <thread>
#include <iostream>

template<typename timer_T = std::chrono::steady_clock>
class my_timer {
public:

    using timer_type = timer_T;
    using time_point = std::chrono::time_point<my_timer, typename timer_T::time_point::duration >;
    using duration   = typename timer_T::duration;
    using rep    = typename duration::rep;
    using period     = typename duration::period;

    static const bool is_steady = timer_T::is_steady;

    static time_point now() {
        return time_point(timer_T::now() - epoch_);
    }

private:
    static typename timer_T::time_point epoch_;
};

template<typename T>
typename T::time_point my_timer<T>::epoch_ = T::now();


int main(int, char*[]) {
    for(int i=0; i<5; i++) {
        std::cout << my_timer<>::now().time_since_epoch().count() << "\n";
        std::this_thread::sleep_until( my_timer<>::now() + std::chrono::seconds(3) );
    }
}

工作here

【讨论】:

  • 实际上我已经尝试过了,但问题是,它并没有很好地工作。现在它仍然无法在 visual studio 2013 中工作... |(我尝试使用 boost chrono 并且很好...我认为使用 std::chrono 的实现也存在问题(再次)对于 msvc。
  • 刚看了VS2013的实现,是的,不兼容……建议你在Microsoft connect上填个bug报告。
  • here 来了。
猜你喜欢
  • 1970-01-01
  • 2011-03-22
  • 1970-01-01
  • 1970-01-01
  • 2019-11-28
  • 2016-09-21
  • 1970-01-01
  • 2022-12-09
  • 1970-01-01
相关资源
最近更新 更多