如何从 <chrono> 获取持续时间,如 int 毫秒和浮点秒数?

2021-12-31 00:00:00 timer c++ c++11 chrono

我正在尝试将 chrono 库用于计时器和持续时间.

I'm trying to use chrono library for timers and durations.

我希望能够有一个 Duration frameStart;(从应用程序开始)和 Duration frameDelta;(帧之间的时间)

I want to be able to have a Duration frameStart; ( from app start ) and a Duration frameDelta; ( time between frames )

我需要能够将 frameDelta 持续时间设为毫秒和浮点秒.

I need to be able to get the frameDelta duration as milliseconds and float seconds.

您如何使用新的 c++11 <chrono> 库来做到这一点?我一直在研究它并使用谷歌搜索(信息很少).代码是大量模板化的,需要特殊的转换和东西,我不知道如何正确使用这个库.

How do you do this with the new c++11 <chrono> libraries? I've been working on it and googling ( information is sparse ). The code is heavily templated and requires special casts and things, I can't figure out how to use this library correctly.

推荐答案

这是您要找的吗?

#include <chrono>
#include <iostream>

int main()
{
    typedef std::chrono::high_resolution_clock Time;
    typedef std::chrono::milliseconds ms;
    typedef std::chrono::duration<float> fsec;
    auto t0 = Time::now();
    auto t1 = Time::now();
    fsec fs = t1 - t0;
    ms d = std::chrono::duration_cast<ms>(fs);
    std::cout << fs.count() << "s
";
    std::cout << d.count() << "ms
";
}

我打印出来的:

6.5e-08s
0ms

相关文章