TheCherno / Sparky

Cross-Platform High Performance 2D/3D game engine for people like me who like to write code.
Apache License 2.0
1.09k stars 222 forks source link

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

Open Hibbel opened 8 years ago

Hibbel commented 8 years ago

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;
eatplayhate commented 8 years ago

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.