1
\$\begingroup\$

I have made this class. Not sure if there is anyway to make it better. It seems to work alright half the time, but other times frames jump up higher then the set limit around 30frames more if i set it to 200fps. I'm using it in a hooked directx function to limit games fps.

Timer.hpp

class Timer
{
public:
    Timer();
    double GetMilisecondsElapsed();
    double GetSecondsElapsed();
    void Restart();
    bool Stop();
    bool Start();
    bool IsRunning() { return isrunning; };
private:
    bool isrunning = false;
    std::chrono::system_clock::time_point start;
    std::chrono::system_clock::time_point stop;
};

Timer.cpp

#include "Timer.hpp"

Timer::Timer()
{
    start = std::chrono::system_clock::now();
    stop = std::chrono::system_clock::now();
}

double Timer::GetMilisecondsElapsed()
{
    if (isrunning) {
        std::chrono::duration<double, std::milli> elapsed = std::chrono::system_clock::now() - start;
        return elapsed.count();
    }
    else {
        std::chrono::duration<double, std::milli> elapsed = stop - start;
        return elapsed.count();
    }
}

double Timer::GetSecondsElapsed()
{
    return GetMilisecondsElapsed() / 1000.0;
}

void Timer::Restart()
{
    isrunning = true;
    start = std::chrono::system_clock::now();
}

bool Timer::Stop()
{
    if (!isrunning)
        return false;
    else {
        stop = std::chrono::system_clock::now();
        isrunning = false;
        return true;
    }
}

bool Timer::Start()
{
    if (isrunning)
        return false;
    else {
        start = std::chrono::system_clock::now();
        isrunning = true;
        return true;
    }
}

FPSLimiter.hpp

class FPSLimiter
{
public:
    FPSLimiter();
    void Pulse(double maxfps);
private:
    Timer t;
};

FPSLimiter.cpp

#include "FPSLimiter.hpp"
#include <chrono>
#include <thread>


FPSLimiter::FPSLimiter()
{
    t.Start();
}

void FPSLimiter::Pulse(double maxfps)
{
    t.Stop();

    if (t.GetMilisecondsElapsed() < (1000.0 / maxfps))
    {
        std::chrono::duration<double, std::milli> delta_ms((1000.0 / maxfps) - t.GetMilisecondsElapsed());
        auto delta_ms_duration = std::chrono::duration_cast<std::chrono::milliseconds>(delta_ms);
        if(delta_ms_duration > std::chrono::milliseconds(0))
            std::this_thread::sleep_for(std::chrono::milliseconds(delta_ms_duration.count()));

    }
    t.Start();
}
\$\endgroup\$
  • 1
    \$\begingroup\$ Can you give a little bit more context to your code? What exactly is it supposed to do? \$\endgroup\$ – IEatBagels Aug 12 '19 at 15:53
  • \$\begingroup\$ Why was this flagged as spam? It is off-topic as we don't have a good idea of what it does, but it's certainly not spam... \$\endgroup\$ – user34073 Aug 13 '19 at 21:24

Browse other questions tagged or ask your own question.