c++ - 计时库中的计数时间点

标签 c++ time c++-chrono

我是第一次使用 chrono 库,所以请宽容 C:。所以我想编写一个简单的获取时间函数,它只返回带有计时的处理器控制。但是当我尝试使用 clock() 函数从使用 steady_clock::now() 初始化的时间点获取值时,gcc 说 time_point 不包含 count() 成员。

/home/siery/Documents/Project/ChangeStateMachine/main.cpp|41|error: ‘struct std::chrono::time_point<std::chrono::_V2::steady_clock, std::chrono::duration<long long int, std::ratio<1ll, 1000000000ll> > >’ has no member named ‘count’|

代码如下:

float GetTime()
{
    float tic = 0.0;
    auto start = std::chrono::steady_clock::now();

    tic = (float)start.count();

    return tic;
}

谢谢!

编辑:

GetTime() 函数应返回当前时间以计算增量时间以频繁更新我程序中的对象,例如:

fPastTime = fCurrentTime;
fCurrentTime = GetTime();

fDt = fCurrentTime - fPastTime;
if (fDt >= 0.15f)
    fDt = 0.15f;
Update(fDt);

最佳答案

建议:

std::chrono::steady_clock::time_point
GetTime()
{
    return std::chrono::steady_clock::now();
}

如果您想要以基于 float 的秒为单位的计时结果,请执行以下操作:

using fsec = std::chrono::duration<float>;
auto t0 = GetTime();
some_function();
auto t1 = GetTime();
fsec delta = t1 - t0;
std::cout << delta.count() << "s\n";
  • 您不对任何单位转换负责,因此您不会在该区域引入任何错误。
  • 代码很简单。简单 == 低风险。
  • 确实不需要 GetTime() 包装器。

编辑:

#include <chrono>

using namespace std::chrono;

using fsec = duration<float>;
using ftp = time_point<steady_clock, fsec>;

ftp
GetTime()
{
    return steady_clock::now();
}

int
main()
{
    auto fPastTime = GetTime();
    auto fCurrentTime = GetTime();

    auto fDt = fCurrentTime - fPastTime;
    if (fDt >= 0.15s)
        fDt = 0.15s;
    // ...
}

0.15s 需要 C++14。在 C++11 中看起来像:

    if (fDt >= fsec{0.15})
        fDt = fsec{0.15};

关于c++ - 计时库中的计数时间点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39113863/

相关文章:

java - 为什么 getStamp() 返回相同的值?

time - 查看大小写错误的数据时,Vue.js 会引发错误

c++ - std::chrono::duration 类型的 volatile 对象

c++ - 将两个 chrono::durations 除以得到分数

c++ - 有没有办法让函数返回一个类型名?

c++ - 约束成员函数和显式模板实例化

c++ - 均衡对象时复制数组

algorithm - 使用 timeit 或 time 计时两个算法(python)

c++ - 带有查找表的霍夫曼码

c++ - Mingw、boost 和运行时 "procedure entry point could not be located"