How to convert std::chrono::duration to double (seconds)?

Přemysl Šťastný picture Přemysl Šťastný · Aug 17, 2019 · Viewed 7k times · Source

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.

Answer

Acorn picture Acorn · Aug 17, 2019

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.