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

血红的双手。 提交于 2020-05-23 21:19:40

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/57538507/how-to-convert-stdchronoduration-to-double-seconds

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!