c++ - 如何在 double 中存储 chrono 的时间?

标签 c++ c++11 c++-chrono

我有一个私有(private)成员的类:

std::chrono::duration<double> _time;

在一个成员函数中我有:

auto time = std::chrono::high_resolution_clock::now();
auto deltaTime  = time - _time;
.
.
.
_time = time;

我想将 deltaTime 用于其他需要 double 值的事情,但我不知道如何将它变成一个。所有的 chrono 教程似乎只是打印结果,从不将其更改为双...

例如..

double dTime = convert(deltaTime); // converts time to nanoseconds

最佳答案

我不知道你到底想做什么,但这是一个常见的模式。假设您想要执行一个循环,并获取每次迭代所花费的秒数,以便将其传递给某个需要代表秒数的 double 的函数。

using clock_t = std::chrono::high_resolution_clock;

// this is a time_point
auto lastIteration = clock_t::now();

while (true) {
    // this is a time_point
    auto thisIteration = clock_t::now();

    // time_point - time_point = duration
    auto elapsed = thisIteration - lastIteration;
    lastIteration = thisIteration;

    // don't need to pass ratio, because default is 1/1, which is seconds
    double seconds = std::chrono::duration<double>(elapsed).count();
    someFunction(seconds);
}

如果你想要纳秒,你当然可以将秒乘以 10 亿。或者你可以使用:

double nanoseconds = std::chrono::duration<double, std::nano>(elapsed).count();

关于c++ - 如何在 double 中存储 chrono 的时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48605420/

相关文章:

c++ - 从本地应用程序向浏览器推送数据

c++ - std::function 是否允许在其返回类型中从引用到拷贝进行隐式转换?

C++ - 我们如何在 Linux 中获得毫秒时间戳?

c++ - g++ vs intel/clang 参数传递顺序?

c++ - 如何将 std::chrono::zoned_time 转换为 std::string

c++ - 如何访问私有(private)变量?

c++ - 更通用的访问者模式

c++ - 通过创建 'state snapshot' 构建撤消和重做

c++ - 在没有隐式转换的情况下在编译时检测运算符

c++ - 分配二维可变大小的数组