Home > Enterprise >  How to use clock_cast?
How to use clock_cast?

Time:05-20

I would like to convert time points from different clocks. Currently I follow the suggestion from here.

static auto ref_sys_clk = std::chrono::system_clock::now();
static auto ref_std_clk = std::chrono::high_resolution_clock::now();

auto to_sys_clk(std::chrono::high_resolution_clock::time_point tp)
{
    //return std::chrono::clock_cast<std::chrono::system_clock::time_point>(tp);
    return ref_sys_clk   std::chrono::duration_cast<std::chrono::system_clock::duration>(tp - ref_std_clk);
}

How can I utilize clock_cast for this purpose. Currently I use Visual Studio 2019.

CodePudding user response:

std::chrono::high_resolution_clock does not participate in the std::chrono::clock_cast facility. The reason for this is that high_resolution_clock, has no portable relationship to any human calendar. It might have one on some platforms, notably if it is a type alias for system_clock. But it definitely does not on all platforms.

Here is a list of clocks that participate in the clock_cast infrastructure:

  • std::chrono::system_clock
  • std::chrono::utc_clock
  • std::chrono::tai_clock
  • std::chrono::gps_clock
  • std::chrono::file_clock
  • Any user-written clock that supplies the static member functions to_sys/from_sys, or to_utc/from_utc.

See the Update for C 20 section of this answer for an example of how to add these functions for your custom clock.

Any clock that does not have the static member functions to_sys/from_sys, or to_utc/from_utc will fail to compile when used in a clock_cast as either the source or destination.

Here is an example use of clock_cast being used to convert from a system_clock-based time_point to a utc_clock-based time_point at a precision of milliseconds.

auto t = sys_days{July/1/2015} - 500ms;
auto u = clock_cast<utc_clock>(t);

CodePudding user response:

std::clock_cast is new in C 20, so if you have a C 11 implementation, you are out of luck. Some implementations still haven't fully implemented C 20, so you may still be out of luck. Unfortunately there doesn't seem to be a feature test macro defined for std::clock_cast, so you will have to check your complier's documentation.

The first parameter of std::chrono::clock_cast is the destination clock, not the desired time_point.

auto to_sys_clk(std::chrono::high_resolution_clock::time_point tp)
{
    return std::chrono::clock_cast<std::chrono::system_clock>(tp);
}
  • Related