• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
Sythical

Timer class not working properly

16 posts in this topic

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!

0

Share this post


Link to post
Share on other sites

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

1

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites

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

0

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites

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
1

Share this post


Link to post
Share on other sites

 

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
1

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites

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
1

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  
Followers 0