我有一个私有(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/