Chrono Timer Not Converting Seconds Properly

偶尔善良 提交于 2019-12-04 21:31:42

std::chrono::seconds et al. are all specified to have integral representations (C++11 §20.11.2 [time.syn]). When you convert a high-resolution duration to a low-resolution duration, you are performing integer division with resulting truncation, e.g,

using namespace std::chrono;
assert(duration_cast<seconds>(milliseconds{999}) == seconds{0});

You can avoid this truncation by switching to a floating point representation before scaling instead of after:

using namespace std::chrono;
currentElapsed = duration_cast<duration<float,std::milli>>(Time::now() - m_timestamp).count();

(Demo at coliru)

Better yet, store currentElapsed as a duration to keep the "units" associated with the magnitude:

class Timer {
    typedef std::chrono::high_resolution_clock Time;
    typedef std::chrono::duration<float> duration;

    Time::time_point m_timestamp;
    duration currentElapsed;

public:
    Timer() : m_timestamp(Time::now()) {}

    duration getTimeElapsed() const {
        return currentElapsed;
    }

    void Tick() {
        auto now = Time::now();
        currentElapsed = now - m_timestamp;
        m_timestamp = now;
    }
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!