Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

The most successful competitive game engines like id Tech, GoldSrc, Source and such allow for framerate limitations.

You can play with 30, with 60, with 99, with 72, with 68 etc. In short, you can cap it and control the cap.

I was wondering, how do I limit the framerate?

Not interested in code, but theory.

share|improve this question
    
Just out of curiosity, what's the point in this other than freeing up cycles for other processes? –  David Lively Jun 14 '12 at 14:52
1  
@DavidLively, Think about laptops, those overheat very easily on a very high frame rate, while with a cap of 60fps (more is useless anyway, even 60 is a bit much, 40 should do) they can control the temperature much better. –  MrMichael Jun 15 '12 at 9:40
    
For competitive gaming it's best to have an even frame rate instead of spikes between 60 and 100 fps since sometimes some actions are frame rate dependent and not time dependent, an equal frame rate lets you get a feel for these actions. Btw note that if you enable VSync your game always has a max fps equal to your refresh rate because (the driver takes care of this). –  Roy T. Jun 15 '12 at 9:50
    

2 Answers 2

up vote 5 down vote accepted

The theory is: Check when you last rendered a frame, and if it's not time to draw another frame yet, then don't, and wait until it is.

share|improve this answer

Say you want to limit your framerate to 60fps, that means that every frame has a render time of 1/60s = 16,67ms (rounded)

To limit your frame rate you just check the time at the start of your game loop, you can then compare it with the time at the end of the game loop: if the difference is less than 16.67ms you should stall for that time.

One way to do this is to use:

sleep(waittime)

However since sleep(x) yields the thread for a minimum of x miliseconds you don't know for certain if you will get control back in time.

A better way would be to use:

while(timediff < 16.67ms){ sleep(0); }

This yields the thread and requests control back as soon as possible.

Another solution is to just have a busy wait loop, this gives you the best control but uses the CPU needlessly.

Remember that the OS scheduler can always take away control from your thread so be prepared for some fluctuation.

share|improve this answer
    
"1/60s" to be clear. :) –  Richard Marskell - Drackir Jun 14 '12 at 14:40

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.