Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

chrono

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.

like image 858
Přemysl Šťastný Avatar asked Aug 17 '19 17:08

Přemysl Šťastný


People also ask

What is std :: Chrono :: duration?

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 .

Which Chrono function allows us to convert a clock duration from one unit to the other?

std::chrono::duration_cast.

What is Chrono C++?

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.


2 Answers

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.

like image 138
Acorn Avatar answered Oct 09 '22 11:10

Acorn


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.

like image 31
Trake Vital Avatar answered Oct 09 '22 10:10

Trake Vital