Jump to content

  • Log In with Google      Sign In   
  • Create Account

Timer class not working properly


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
16 replies to this topic

#1 Sythical   Members   -  Reputation: 138

Like
0Likes
Like

Posted 06 July 2013 - 01:13 AM

Hello, I've written a timer class in C++ but it's not working properly. The trouble I'm having is that after a couple of minutes the animation becomes choppy. It sometimes fixes automatically after about 5 ~ 60 seconds.

#include <windows.h>

class Timer {

	int sleep_length_ms;
	double ratio;
	LONGLONG duration, next_mark;
	LARGE_INTEGER counter, frequency;

public:
	Timer(int frame_rate) {
		QueryPerformanceCounter(&counter);
		QueryPerformanceFrequency(&frequency);

		duration = frequency.QuadPart / frame_rate;
		next_mark = counter.QuadPart + duration;
		ratio = 1000.0 / frequency.QuadPart;
	}

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

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

		return true;
	}
};

This is how the class if used in a game loop:

Timer timer(60);

while(run_game) {
	update_game();
	render_game();

	timer.wait();
}

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!



Sponsor:

#2 Tribad   Members   -  Reputation: 887

Like
1Likes
Like

Posted 06 July 2013 - 01:21 AM

Sleep is evil. AFAIK the resolution of Sleep is that of the task scheduler timer. 20ms? Searching for that topic should help you out.



#3 Sythical   Members   -  Reputation: 138

Like
0Likes
Like

Posted 06 July 2013 - 01:25 AM

I know that Sleep provides no guarantee that the thread will "wake up" after the specified duration but I also don't want to rely on a do while loop for timing. I read through the relavent source files of Allegro and it also uses Sleep in the timer thread and it seems to work perfectly.



#4 Tribad   Members   -  Reputation: 887

Like
0Likes
Like

Posted 06 July 2013 - 01:45 AM

Add a check code. sleep_length_ms cannot be longer than the period of the timer. for your example 16ms. So if it is larger than 0 but even larger than the timer period something goes wrong.



#5 Tispe   Members   -  Reputation: 1044

Like
1Likes
Like

Posted 06 July 2013 - 03:09 AM

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;
}


#6 Sythical   Members   -  Reputation: 138

Like
0Likes
Like

Posted 06 July 2013 - 03:10 AM

Thank you for the suggestion. I just tried that and sleep_length_ms fluctuates between 16 and 17 so that seems fine. When the animation finally starts to stutter, sleep_length_ms is still 16 or 17. I also added a check to let me know when Sleep() makes the thread oversleep and that doesn't seem to be the problem either. So confusing, it's probably a silly mistake somewhere that I can't spot.



#7 Tispe   Members   -  Reputation: 1044

Like
0Likes
Like

Posted 06 July 2013 - 03:14 AM

Try this with my timer. 

GameTimer FrameTimer;
while(run_game) {
if(FrameTimer.HasElapsed(60))       //Render every 60ms
{
	update_game();
	render_game();
}
else
{
Sleep(0)
 }
}

Edited by Tispe, 06 July 2013 - 03:16 AM.


#8 Sythical   Members   -  Reputation: 138

Like
0Likes
Like

Posted 06 July 2013 - 03:58 AM

I was using something similar to the code you posted but the CPU usage was around 25%. I know that there isn't exactly anything wrong with that and it's normal for games but I wanted to try and write a CPU efficient timer.



#9 Tispe   Members   -  Reputation: 1044

Like
0Likes
Like

Posted 06 July 2013 - 04:13 AM

You can maybe get away with using Sleep(1).

 

I would decouple update_game() from render_game(). Such that update_game() works independently on FPS. Which means you need to pass it the elapsed time every time you call it and only update incrementally based on elapsed time. That way animation will be smooth and consistant regardless of FPS. This will cure your stuttering problems.

GameTimer FrameTimer;
GameTimer UpdateTimer;
while(run_game) {

update_game(UpdateTimer.Tick());

if(FrameTimer.HasElapsed(20)) {
	render_game();
} else {
Sleep(1);
 }

}

Edited by Tispe, 06 July 2013 - 04:18 AM.


#10 Sythical   Members   -  Reputation: 138

Like
0Likes
Like

Posted 06 July 2013 - 04:25 AM

I considered using Sleep(1) but I believe it'll make thread oversleep fairly often. Another thing I tried was make the thread sleep for 70% of the required time and then rely on a do while loop for the remainder of the duration. That was fairly accurate and the dropped the usage to 10%. I'll follow your advice and decouple the physics/logic and rendering, I have read the fix your timestep article and implement that but my GPU's fan started making an unpleasant noise (the whole reason why I got obsessed with CPU/GPU usage).



#11 Tispe   Members   -  Reputation: 1044

Like
0Likes
Like

Posted 06 July 2013 - 04:39 AM

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.



#12 Sythical   Members   -  Reputation: 138

Like
0Likes
Like

Posted 06 July 2013 - 04:46 AM

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



#13 DareDeveloper   GDNet+   -  Reputation: 976

Like
1Likes
Like

Posted 06 July 2013 - 05:07 AM

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".


Edited by DareDeveloper, 06 July 2013 - 05:35 AM.

Given enough eyeballs, all mysteries are shallow.

ProcGames.com


#14 Vortez   Crossbones+   -  Reputation: 2704

Like
1Likes
Like

Posted 06 July 2013 - 07:42 AM

 

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.


Edited by Vortez, 06 July 2013 - 08:55 AM.


#15 Tispe   Members   -  Reputation: 1044

Like
0Likes
Like

Posted 06 July 2013 - 07:46 AM

Jupp, but I added HasElapsed happy.png



#16 Sythical   Members   -  Reputation: 138

Like
0Likes
Like

Posted 06 July 2013 - 09:44 AM

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


Edited by Sythical, 06 July 2013 - 10:04 AM.


#17 DareDeveloper   GDNet+   -  Reputation: 976

Like
1Likes
Like

Posted 06 July 2013 - 10:31 AM

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.


Edited by DareDeveloper, 06 July 2013 - 10:36 AM.

Given enough eyeballs, all mysteries are shallow.

ProcGames.com





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS