c++ - 如何重置 high_resolution_clock::time_point

标签 c++ c++11 c++-chrono

我正在开发一个类 Timer它的一些成员属于 high_resolution_clock::time_point 类型其中 time_point定义为 typedef chrono::time_point<system_clock> time_point;

问题

这个对象的默认值是多少?

出于以下几个原因,我需要了解此值:

  1. 知道成员是否被初始化
  2. 实现 Timer::Reset()功能

背景

class Timer
{
    void Start() { m_tpStop = high_resolution_clock::now(); }
    void Stop() { m_tpStart = high_resolution_clock::now(); }

    bool WasStarted() { /* TO-DO */ }

    void Reset();
    __int64 GetDuration();

    high_resolution_clock::time_point m_tpStart;
    high_resolution_clock::time_point m_tpStop;
};

那么,我可以实现Timer::WasStarted吗?通过只看成员m_tpStart ?我不想为此添加 bool 值成员。

最佳答案

So, can I implement Timer::WasStarted by looking only at member m_tpStart?

好吧,如果您定义这样的不变量,当且仅当计时器被重置(未启动)时,m_tpStart 为零(纪元),那么它是微不足道的。只需检查 start 是否为 epoch 即可测试定时器是否启动。

具体如何将时间点设置为纪元,似乎有点令人费解 - 我想这就是您所说的“如何重置 high_resolution_clock::time_point”。您需要复制分配一个默认构建的时间点。

void Start() { m_tpStart = high_resolution_clock::now(); }
void Stop() {
    m_tpStop = high_resolution_clock::now();
}
bool WasStarted() {
    return m_tpStart.time_since_epoch().count(); // unit doesn't matter
}
void Reset() {
    m_tpStart = m_tpStop = {};
}

关于c++ - 如何重置 high_resolution_clock::time_point,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35148465/

相关文章:

c++ - 如何在 double 中存储 chrono 的时间?

c++ - std::cin 在不应该接收输入时接收输入

c++ - 为什么 'is_convertible' 在 <utility> std::pair (STL) 中?

visual studio 2015 RC 访问冲突中的 C++ 可恢复函数(yield)

c++ - 错误 : variable has incomplete type 'introstructions' can't understand

c++ - ostream_iterator for vector<vector<double>>

c++ - vector 迭代器错误

c++ - thread_guard 与 scoped_thread

c++ - 你什么时候使用 std::unordered_map::emplace_hint?

c++ - 如何判断我的 struct tm 是否处于无效状态?