简体   繁体   English

如何将 std::chrono::duration 转换为双倍(秒)?

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

Let's have using duration = std::chrono::steady_clock::duration .让我们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.或者表示,我想要一些 std function double F(duration) ,它返回秒。

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 .如果您需要std::chrono::duration构造函数无法完成的更复杂的强制转换,请使用std::chrono::duration_cast

Converting a std::chrono::duration to any numeric "count" is deceptively simple!std::chrono::duration转换为任何数字“计数”看似简单!

You can divide any two std::chrono::duration s to efficiently get a count.您可以任意两个std::chrono::duration相除以有效地获得计数。

Given a duration d of any period and any integer representation:给定任何时期的持续时间d和任何 integer 表示:

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.但是我不知道精度......虽然这种方法非常精确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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