Sparky icon indicating copy to clipboard operation
Sparky copied to clipboard

[Sparky-core] Steady timer instead of system timer.

Open Hibbel opened this issue 9 years ago • 1 comments
trafficstars

In your utils/Timer.h you should use std::chrono::steady_clock instead of std::chrono::high_resolution_clock. The high_resolution_clock depends on the systems time which means that when you change your time, the clock will behave akwardly. So you can set your systems time to the future and your game will go insane.

To fix this issue just use the std::chrono::steady_clock which is based on your systems internal time counter.

Optional: I would call the class a StopWatch rather than a timer.

Here's the way i implemented it:

template<typename Res>
class StopWatch
{
private:
    std::chrono::steady_clock::time_point m_start;

public:
    StopWatch()
    {
        restart();
    }

    long getElapsedTime()
    {
        return (long)std::chrono::duration_cast<Res>(std::chrono::steady_clock::duration(std::chrono::steady_clock::now() - m_start)).count();
    }

    void restart()
    {
        m_start = std::chrono::steady_clock::now();
    }
};

typedef StopWatch<std::chrono::nanoseconds> StopWatchNs;
typedef StopWatch<std::chrono::microseconds> StopWatchUs;
typedef StopWatch<std::chrono::milliseconds> StopWatchMs;
typedef StopWatch<std::chrono::seconds> StopWatchS;
typedef StopWatch<std::chrono::minutes> StopWatchM;
typedef StopWatch<std::chrono::hours> StopWatchH;

Hibbel avatar Nov 29 '15 14:11 Hibbel

The assumption up until now is that Timer is for timing/performance measurement, due to that it should use high resolution timers, but I agree it should be renamed to StopWatch. Making a variant of it which uses steady timer makes sense.

Of course, I also would advocate for using QueryPerformanceCounter/gettimeofday/mach_absolute_time as well.

eatplayhate avatar Apr 15 '16 11:04 eatplayhate