简体   繁体   中英

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

Let's have using duration = std::chrono::steady_clock::duration . I would like to convert duration to double in seconds with maximal precision elegantly.

I have found the reverse way , but it didn't help me finding it out.

Alternatively expressed, I want optimally some std function double F(duration) , which returns seconds.

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 , usestd::chrono::duration_cast .

Converting a std::chrono::duration to any numeric "count" is deceptively simple!

You can divide any two std::chrono::duration s to efficiently get a count.

Given a duration d of any period and any integer representation:

using std::chrono_literals;

// Want to know how many seconds?  Divide by one second!
std::int64_t int_seconds = d / 1s;
double       fp_seconds  = d / 1.0s;

As shown, it does not matter what the period is of the two durations. And the resulting type will be the common type of the two durations.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM