2

I'm develoiping a class Timer that some of its members are of type high_resolution_clock::time_point where time_point is defined as typedef chrono::time_point<system_clock> time_point;

Question

What is the default value of this object?

I need to be aware of this value from couple of reasons:

  1. Know if member was initialized
  2. Implement Timer::Reset() function

Background

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;
};

So, can I implement Timer::WasStarted by looking only at member m_tpStart? I'd like to refrain from adding a boolean member for that purpose.

Community
  • 1
  • 1
idanshmu
  • 5,061
  • 6
  • 46
  • 92
  • Have you read [some](http://en.cppreference.com/w/cpp/chrono/time_point) [docs](http://en.cppreference.com/w/cpp/chrono/time_point/time_point)? – Ivan Aksamentov - Drop Feb 02 '16 at 08:36
  • Possible duplicate of [When is std::chrono epoch?](http://stackoverflow.com/questions/29799293/when-is-stdchrono-epoch) – Ivan Aksamentov - Drop Feb 02 '16 at 08:41
  • What do you want the `Timer::Reset()` to do? What does resetting a timer mean? – eerorika Feb 02 '16 at 08:52
  • I've just updated the question. Please look at the class itself. Hope it'll clear it up. – idanshmu Feb 02 '16 at 08:56
  • @user2079303, I understand the `Timer::Reset()` function needs more details. So, for simplicity, let's focus on implementation of function `Timer::WasStarted`. Can it be implemented in a simple manner? – idanshmu Feb 02 '16 at 08:58

1 Answers1

8

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

Well, if you define such invariant, that m_tpStart is zero (the epoch) if and only if the timer is reset (not started), then it's trivial. Simply check whether start is epoch to test if the timer is started.

Exactly how to set a time point to epoch, seems to be slightly convoluted - and I guess that's what you're referring to with "How to reset the high_resolution_clock::time_point". You'll need to copy-assign a default constructed 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 = {};
}
eerorika
  • 232,697
  • 12
  • 197
  • 326
  • how would you implement `GetDuration()` with this? – sp2danny Feb 02 '16 at 09:44
  • @sp2danny I changed the code, to not reset start when stopping the timer. This is better for OP's design. `GetDuration` is simple now. Subtract and cast. – eerorika Feb 02 '16 at 09:56