I have the following code which works fine:
auto my_time = std::chrono::system_clock::now();
std::cout << "My Time is " << std::chrono::system_clock::to_time_t(my_time) << std::endl;
However, if I replace system_clock with high_resolution_clock like below:
auto my_time = std::chrono::high_resolution_clock::now();
std::cout << "My Time is " << std::chrono::high_resolution_clock::to_time_t(my_time) << std::endl;
I got the following error:
no member named 'to_time_t' in 'std::__1::chrono::steady_clock'
std::cout << "My Time is " << std::chrono::high_resolution_clock::to_time_t(my_time) << std::endl;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
1 error generated.
Any idea how to make high_resolution_clock works here? (I am benchmarking some functions, so would like to use high_resolution_clock rather than system_clock) Thanks!
In general, it is not possible to convert chrono::high_resolution_clock::time_point to time_t. It is not just because it lacks a to_time_t member function. It is because:
There is absolutely no relationship between the time
time_tmeasures and the timehigh_resolution_clock::time_pointmeasures.
Think of high_resolution_clock as a stopwatch. You can use it to measure the time it took for some event to happen. But you can't tell the time of day with it.
On my platform, high_resolution_clock measures the number of nanoseconds since the system booted up. If you don't know what time the system booted, there's no way to translate high_resolution_clock into a time of day.
time_t on the other hand typically measures time since 1970-01-01 00:00:00 UTC, and so does have a relationship to the time-of-day.
On your system, high_resolution_clock is aliased to steady_clock, which is not required by the standard to implement to_time_t. It's possible that the two are incompatible, e.g. if time_t is seconds since epoch, and high_resolution_clock::period is smaller than 1 second, then you couldn't represent a high_resolution_clock::time_point as a time_t without a loss of precision.
If you are using this for benchmarking, you can probably skip the conversion to time_t altogether. Just do something like:
auto start = std::chrono::high_resolution_clock::now();
my_function();
auto end = std::chrono::high_resolution_clock::now();
std::cout << "my_function took " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << " ms" << std::endl;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With