Timer class not working properly

Started by
15 comments, last by DareDeveloper 10 years, 9 months ago

What graphics API are you using?

Normally render_game() would block to synchronize with your monitors refresh rate. This is the standard way to reduce CPU usage.

Advertisement

Yea, I'm using SFML and it has a setVerticalSyncEnabled() function.

Have you logged how many times the else-block is executed?


...
		if(sleep_length_ms > 0) {
			Sleep(sleep_length_ms);
			next_mark += duration;					
		} else {
			// if running behind
			QueryPerformanceCounter(&counter);
			next_mark = counter.QuadPart + duration;
		}
...

I'm testing this class using a simple Allegro program where a circle bounces off the edges. I tried using the timer class provided by Allegro and the issue resolves so I'm quite sure that the problem lies within my timer class. I can't seem to figure out what I'm doing wrong and would be very grateful if someone can have a read through the code. Thank you!

Not sure ... it looks suspicious somehow. Is it important to read the time again there? What about a code like that:


    bool wait() {
        bool slept = false;

        QueryPerformanceCounter(&counter);
        sleep_length_ms = (int) (ratio * (next_mark - counter.QuadPart));

        if(sleep_length_ms > 0) {
            Sleep(sleep_length_ms);
            updated = true;
        }
        next_mark += duration;

        return slept;
    }

Timer timer(60);

bool slept = false;
while(run_game)
{
    update_game();
    render_game();

    do {
       slept = timer.wait();
    } while (!slept)
}

Probably it is something else entirely ... but it looks more regular (wait always uses duration steps ... even if it might skip one frame).

Edit: ok that is ugly and causes a sleep when already running behind ... I think I'd try to turn wait() into two functions and pass the current time to them:

wait(currentTime) and updateNextMark(currentTime) that doesn't read the time again and increments next_mark until it is bigger than the current time.

Currently wait() is a little "side-effecty".

Given enough eyeballs, all mysteries are shallow.

MeAndVR

Here is mine. I use the "HasElapsed" function to do things periodically in a main loop. For example, you can send a packet every 20ms by calling HasElapsed.


#pragma once
class GameTimer
{
public:
	GameTimer(void);
	~GameTimer(void);

	void  Reset();
	float Tick();
	bool HasElapsed(float milliseconds);

private:
	bool    IsPerfCounterAvailable;
	float   TimeScale;
	__int64 PerfCounterFrequency;
	__int64 LastTime;
	__int64 CurrentTime;	
};


GameTimer::GameTimer(void)
{
	//Check if a High resolution timer is available 
	if(QueryPerformanceFrequency((LARGE_INTEGER*)&PerfCounterFrequency)){ 
		IsPerfCounterAvailable = true;
		QueryPerformanceCounter((LARGE_INTEGER*)&CurrentTime); 
		TimeScale = 1.0f / PerfCounterFrequency;
	} else { 
		IsPerfCounterAvailable = false;
		CurrentTime = timeGetTime(); 
		TimeScale	= 0.001f;
    } 
	
	Reset();
}


GameTimer::~GameTimer(void)
{
}

bool GameTimer::HasElapsed(float milliseconds)
{
	if(IsPerfCounterAvailable){
		QueryPerformanceCounter((LARGE_INTEGER*)&CurrentTime);
	} else {
		CurrentTime = timeGetTime();
	}

	if( ((CurrentTime - LastTime) * TimeScale) > (milliseconds*0.001f))
	{
		LastTime = CurrentTime;
		return true;
	}

	return false;
}

float GameTimer::Tick()
{
	LastTime = CurrentTime;

	if(IsPerfCounterAvailable){
		QueryPerformanceCounter((LARGE_INTEGER*)&CurrentTime);
	} else {
		CurrentTime = timeGetTime();
	}

	// Calculate the elapsed time
	float ElapsedTime = (CurrentTime - LastTime) * TimeScale;

	return ElapsedTime;
}

void GameTimer::Reset()
{
	if(IsPerfCounterAvailable){
		QueryPerformanceCounter((LARGE_INTEGER*)&CurrentTime);
	} else {
		CurrentTime = timeGetTime();
	}

	// Initialization
	LastTime = CurrentTime;
}

Lol, that's my code laugh.png . Glad to see someone else found it usefull.

To the op: there's no perfect solution for what you are asking, if you want very high precision wait, you have to burn more cpu cycles, if not, then sleep is fine. Sleep() only have a precision of approx. 16 ms, that's how windows work. I've heard something about select() that could be used for this, with a timeout value, but i never tested it. Even then, the timeout value is still in milliseconds so...

But... what's the issue exactly? Are you trying to get a particular framerate, or are you trying to get a smooth animation of your circle?

My guess is the second one, so, just use the high precision timer shown above and you should be fine. That's how i do it:

In the game loop, i have:


            UpdateScene(Timer.Tick());
            RenderScene();

Then, in the update function, i do the animation


float xCoord, yCoord;

...

void UpdateScene(float ElapsedTime)
{
    xCoord += 1.0f * ElapsedTime;
    yCoord -= 2.5f * ElapsedTime;
}

That's just an example to move something in a straigh line, based on xCoord and yCoord, but it could be anything you want really.

Just scale the value of how many units the object should move, in 1 second, by ElapsedTime and you will have perfect animation no matter the framerate.

If you want to move it only at specified interval of time, then use this:


// 100 ms delay
float Delay = 0.1f;

while(ElapsedTime >= Delay){

    xCoord += 1.0f;
    yCoord -= 2.5f;

    ElapsedTime -= Delay;     // <-- assuming you don't want to use ElasedTime afterward, otherwise, use a copy of it
    if(ElapsedTime < 0.0f)    // <-- optional if... not really needed    
        ElapsedTime = 0.0f;
}

That might look a bit ugly, but it can be wrap in 1 line of code using a function. For the sake of simplicity, i've shown it this way.

Just don't use sleep() for stuffs like that in a game, it's not what it was made for. If you want to save cpu cycles, just turn vsync on.

The full source code for my timer class is here, down at the very bottom of the page.

Edit: Actually, i've polished the code a bit since then, use this instead.

Jupp, but I added HasElapsed happy.png

Have you logged how many times the else-block is executed?

Yup, I've tested that and the else block is only executed once at the start because of the way I'm using the class.

But... what's the issue exactly? Are you trying to get a particular framerate, or are you trying to get a smooth animation of your circle?

Yes you're right, my top priority is to get a smooth animation but I got distracted by trying to minimise CPU usage and wanted to know if I'm doing something wrong in my timer class.

Thank you everyone for the suggestions, I should stop reinventing the wheel and focus on the actual game instead smile.png

I totally think it is worth looking into if the problem always occurs with your timer and never with others.

It is a good habit to get into (builds resilience and it sounds like a bug, not unneccessary optimization).

Usually the way to track down that kind of problem is enclosing code with time1 and time2 ... subtracting time1 from time2 and logging the result (always or when the time is unusual).

Guess a sophisticated profiling solution like the one from the enginuity articles might be a nice thing to have/use: http://archive.gamedev.net/archive/reference/programming/features/enginuity3/index.html

But more simple solutions should help as well. You might be able to narrow it down. It might turn out that it is actually the update or render function for some reason ... or something in wait() that is out of your control. Then you can move on with a different timer and a good feeling.

Given enough eyeballs, all mysteries are shallow.

MeAndVR

This topic is closed to new replies.

Advertisement