How to create a custom chrono clock

别说谁变了你拦得住时间么 提交于 2019-12-21 05:34:09

问题


I'm creating a timeline UI control, and time on this timeline always starts at zero, like a stopwatch. I thought of using std::chrono::steady_clock to keep the start and end time on the scale, however, it feels wrong to have a clock-time here, like '10am march 2017' has nothing to do with the beginning of the scale.

Should I/can I create a custom clock that starts time at '0'?


回答1:


Here is an example custom chrono clock that is based on steady_clock and counts time since the first time it is called (approximately):

#include "chrono_io.h"
#include <chrono>
#include <iostream>

struct MyClock
{
    using duration   = std::chrono::steady_clock::duration;
    using rep        = duration::rep;
    using period     = duration::period;
    using time_point = std::chrono::time_point<MyClock>;
    static constexpr bool is_steady = true;

    static time_point now() noexcept
    {
        using namespace std::chrono;
        static auto epoch = steady_clock::now();
        return time_point{steady_clock::now() - epoch};
    }
};

int
main()
{
    using namespace date;
    std::cout << MyClock::now().time_since_epoch() << '\n';
    std::cout << MyClock::now().time_since_epoch() << '\n';
    std::cout << MyClock::now().time_since_epoch() << '\n';
    std::cout << MyClock::now().time_since_epoch() << '\n';
}

One just needs to define the nested types duration, rep and period which it can just steal from steady_clock, and then create it's own time_point. One should not use steady_clock's time_point because the epoch of MyClock and steady_clock are different, and you don't want to accidentally mix those two time_point's in arithmetic.

Since MyClock is based on steady_clock, it is_steady.

And the now() function stores the current time epoch in a static (evaluated the first time it is called), and then just finds the time since the epoch each time it is called. This subtraction creates a duration, which can be used to construct a MyClock::time_point.

I'm using "chrono_io.h" just because I'm lazy in my formatting. You don't need that header to create your own custom clock. This does nothing but make it easier to print out durations.

This program just output for me:

1618ns
82680ns
86277ns
88425ns


来源:https://stackoverflow.com/questions/42613031/how-to-create-a-custom-chrono-clock

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!