Sign in to follow this  
X Abstract X

My Timer is Off

Recommended Posts

Hello everyone. I'm trying to implement a simple Timer for use in my games but I'm having an issue. My timer will report back an accurate FPS reading whenever I set the maximumFPS to 60 or less. However, if I set it higher (even to 61fps), it returns an average fps that is inaccurate, sometimes as high as 300% more than the maximumFPS that I set. I would really appreciate if someone could look at my code, I believe the trouble is in bool Timer::timeToUpdate(). I really hate to dump this much code but, the variable names are descriptive and I commented the functions in the header - hopefully it is easy to interpret. Thanks.
//HEADER FILE
#ifndef TIMER_H
#define TIMER_H

#include "SDL.h"

class Timer {

private:
	unsigned int maxFPS, frame, startTime, deltaTime;
	double msPerFrame, extraTime, accumulatedFPS, averageFPS;	

public:
	Timer(unsigned int targetFPS) : maxFPS(targetFPS), frame(0), startTime(0), deltaTime(0),
		msPerFrame(1000.0 / (double)targetFPS), extraTime(0.0), accumulatedFPS(0.0), averageFPS(0.0) {}
	~Timer() {}

	void start(); //reset start time
	bool timeToUpdate(); //maintain the update rate of game - for logic
	bool timeToRender() const; //returns true only if the timer is keeping up with maxFPS
	bool eventOnFrame(unsigned int eventFrame) const; //this isn't a concern right now
	void yield() const; //let the os have some time
	double getFPS() const;

};

#endif
//END HEADER FILE

//CPP FILE
#include "Timer.h"

void Timer::start() {
	startTime = SDL_GetTicks();
}

bool Timer::timeToUpdate() {
	deltaTime = SDL_GetTicks() - startTime;

	if (deltaTime >= (msPerFrame - extraTime)) {
		frame++;

		if (deltaTime != 0) {
			accumulatedFPS += (1000.0 / (double)deltaTime);		
		} else {
			accumulatedFPS += (1000.0 / (double)maxFPS);
		}

		if ((frame % 10) == 0) {
			averageFPS = (accumulatedFPS / 10.0);
			accumulatedFPS = 0.0;
		} else if (frame < 10) {
			averageFPS = (accumulatedFPS / (double)frame);
		}

		extraTime += ((double)deltaTime - msPerFrame);
		start();

		return(true);
	}

	return(false);
}

bool Timer::timeToRender() const {
	if (extraTime <= msPerFrame) {
		return(true);
	}

	return(false);
}

bool Timer::eventOnFrame(unsigned int eventFrame) const {
	if ((frame % eventFrame) == 0) {
		return(true);
	}

	return(false);
}

void Timer::yield() const {
	SDL_Delay(0);
}

double Timer::getFPS() const {
	return(averageFPS);
}
//END CPP FILE


Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this