Let's have using duration = std::chrono::steady_clock::duration
. I would like to convert duration to double in seconds with maximal precition elegantly.
I have found the reverse way (convert seconds as double to std::chrono::duration? ), but it didn't help me finding it out.
Alternatively expressed, I want optimally some std function double F(duration)
, which returns seconds.
Thank you.
Class template std::chrono::duration represents a time interval. It consists of a count of ticks of type Rep and a tick period, where the tick period is a compile-time rational fraction representing the time in seconds from one tick to the next. The only data stored in a duration is a tick count of type Rep .
std::chrono::duration_cast.
Chrono library is used to deal with date and time. This library was designed to deal with the fact that timers and clocks might be different on different systems and thus to improve over time in terms of precision.
Simply do:
std::chrono::duration<double>(d).count()
Or, as a function:
template <class Rep, class Period>
constexpr auto F(const std::chrono::duration<Rep,Period>& d)
{
return std::chrono::duration<double>(d).count();
}
If you need more complex casts that cannot be fulfilled by the std::chrono::duration
constructors, use std::chrono::duration_cast
.
This is the most straightforward way for me:
auto start = std::chrono::steady_clock::now();
/*code*/
auto end = std::chrono::steady_clock::now();
std::chrono::duration<double> diff = end - start;
std::cout << "Duration [seconds]: " << diff.count() << std::endl;
however I do not know about precision... Although this method is pretty precise.
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