【问题标题】:How to reset the high_resolution_clock::time_point如何重置 high_resolution_clock::time_point
【发布时间】:2016-05-10 23:06:19
【问题描述】:

我正在开发一个类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;
};

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

【问题讨论】:

  • 你读过somedocs吗?
  • 你想让Timer::Reset()做什么?重置计时器是什么意思?
  • 我刚刚更新了这个问题。请看课程本身。希望它会清除它。
  • @user2079303,我了解Timer::Reset() 函数需要更多详细信息。因此,为简单起见,让我们专注于函数Timer::WasStarted 的实现。能否以简单的方式实现?

标签: c++ c++11 chrono


【解决方案1】:

那么,我可以通过只查看成员 m_tpStart 来实现 Timer::WasStarted 吗?

好吧,如果你定义这样的不变量,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 = {};
}

【讨论】:

  • 你会如何用这个实现GetDuration()
  • @sp2danny 我更改了代码,停止计时器时不重置开始。这对OP的设计来说更好。 GetDuration 现在很简单。减法和投射。
猜你喜欢
  • 2019-02-16
  • 1970-01-01
  • 2015-06-04
  • 2013-05-07
  • 2012-01-13
  • 1970-01-01
  • 1970-01-01
  • 2021-08-19
  • 1970-01-01
相关资源
最近更新 更多