Time measurements with High_resolution_clock not working as intended

蓝咒 提交于 2019-12-12 03:18:41

问题


I want to be able to measure time elapsed (for frame time) with my Clock class. (Problem described below the code.)

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();
}

When I try to use Clock like so

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
 }

For me it prints about 30 times "0" until it finally prints a number which is always very close to something like "15625" microseconds (15.625 milliseconds).

My question is, why isn't there anything between? I'm wondering whether my implementation is wrong or the precision on high_resolution_clock is acting strange. Any ideas?

EDIT: I am using Codeblocks with mingw32 compiler on a windows 8 computer.

EDIT2: I tried running the following code that should display high_resolution_clock precision:

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

int main()
{
    display_precision<std::chrono::high_resolution_clock>();
}

For me it prints: "1000 ns". So I guess high_resolution_clock has a precision of 1 microsecond right? Yet in my tests it seems to have a precision of 16 milliseconds?


回答1:


What system are you using? (I guess it's Windows? Visual Studio is known to had this problem, now fixed in VS 2015, see the bug report). On some systems high_resolution_clock is defined as just an alias to system_clock, which can have really low resolution, like 16 ms you are seeing. See for example this question.



来源:https://stackoverflow.com/questions/31643279/time-measurements-with-high-resolution-clock-not-working-as-intended

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!