High_resolution_clock的时间测量没有按预期工作

Time measurements with High_resolution_clock not working as intended

本文关键字:工作 测量 resolution clock 时间 High      更新时间:2023-10-16

我希望能够使用我的Clock类测量经过的时间(对于帧时间)。(问题描述如下代码)

Clock.h

typedef std::chrono::high_resolution_clock::time_point timePt;
class Clock
{
    timePt currentTime;
    timePt lastTime;
public:
    Clock();
    void update();
    uint64_t deltaTime();
};

Clock.cpp

#include "Clock.h"
using namespace std::chrono;
Clock::Clock()
{
    currentTime = high_resolution_clock::now();
    lastTime = currentTime;
}
void Clock::update()
{
    lastTime = currentTime;
    currentTime = high_resolution_clock::now();
}
uint64_t Clock::deltaTime()
{
    microseconds delta = duration_cast<microseconds>(currentTime - lastTime);
    return delta.count();
}

当我尝试使用时钟像这样

Clock clock;
while(1) {
    clock.update();
    uint64_t dt = clock.deltaTime();
    for (int i=0; i < 10000; i++)
    {
        //do something to waste time between updates
        int k = i*dt;
    }
    cout << dt << endl; //time elapsed since last update in microseconds
 }

对我来说,它打印了大约30次"0",直到最后打印出一个总是非常接近"15625"微秒(15.625毫秒)的数字。

我的问题是,为什么没有介于两者之间?我想知道我的实现是错误的还是high_resolution_clock上的精度表现得很奇怪。什么好主意吗?

编辑:我在windows 8计算机上使用Codeblocks与mingw32编译器。

EDIT2:我尝试运行以下代码,应该显示high_resolution_clock精度:

template <class Clock>
void display_precision()
{
    typedef std::chrono::duration<double, std::nano> NS;
    NS ns = typename Clock::duration(1);
    std::cout << ns.count() << " nsn";
}
int main()
{
    display_precision<std::chrono::high_resolution_clock>();
}

对我来说,它打印:"1000 ns"。我猜high_resolution_clock的精度是1微秒?但在我的测试中,它的精度似乎只有16毫秒。

您使用的是什么系统?(我猜是Windows吧?Visual Studio已知有这个问题,现在在VS 2015中修复了,见bug报告)。在一些系统上,high_resolution_clock被定义为system_clock的别名,它的分辨率很低,比如你看到的16毫秒。请看下面这个问题。

我在Windows 10上使用msys2也有同样的问题:对于我测试的大多数子函数,返回的delta是0,突然返回15xxx或24xxx微秒。我认为我的代码有问题,因为所有的教程都没有提到任何问题。对于time.h中的difftime(finish, start)也是如此,它通常返回0。

我终于把我所有的high_resolution clock换成了steady_clock,我可以找到合适的时间:

auto t_start = std::chrono::steady_clock::now();
_cvTracker->track(image); // my function to test
std::cout << "Time taken = " << std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock ::now() - t_start).count() << " microseconds" << std::endl;
// returns the proper value (or at least a plausible value)

而这返回的大多是0:

auto t_start = std::chrono::high_resolution_clock::now();
_cvTracker->track(image); // my function to test
std::cout << "Time taken = " << std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - t_start).count() << " microseconds" << std::endl;
// returns 0 most of the time

difftime似乎也不起作用:

time_t start, finish;
time(&start);
_cvTracker->track(image);
time(&finish);
std::cout << "Time taken= " << difftime(finish, start) << std::endl;
// returns 0 most of the time