How to create a custom chrono clock

前端 未结 1 701
忘了有多久
忘了有多久 2021-02-10 17:35

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 ti

相关标签:
1条回答
  • 2021-02-10 18:23

    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
    
    0 讨论(0)
提交回复
热议问题