views:

285

answers:

4

Hi,

I'm writing a game, and I saw the FPS algorithm doesn't work correctly (when he have to calculate more, he sleeps longer...) So, the question is very simple: how to calculate the sleeptime for having correct FPS?

I know how long it took to update the game one frame in microseconds and of course the FPS I want to reach.

I'm searching crazy for a simple example, but I can't find one....

The code may be in Java, C++ or pseudo....

+4  A: 

The time you should spend on rendering one frame is 1/FPS, so if it took X seconds to render, you should "sleep" for 1/FPS - X seconds.

If it, for some reason took more than 1/FPS to render the frame, you'll get a negative sleep time in which case you obviously just skip the sleeping.

aioobe
+8  A: 

The number of microseconds per frame is 1000000 / frames_per_second. If you know that you've spent elapsed_microseconds calculating, then the time that you need to sleep is:

(1000000 / frames_per_second) - elapsed_microseconds
JSBangs
@JS Bangs: hmm... same effect... I'm going to check the time fuctions.
Martijn Courteaux
@JS Bangs: Indeed, it were my time functions.... Thanks
Martijn Courteaux
+1  A: 

Try...

static const int NUM_FPS_SAMPLES = 64;
float fpsSamples[NUM_FPS_SAMPLES]
int currentSample = 0;

float CalcFPS(int dt)
{
    fpsSamples[currentSample % NUM_FPS_SAMPLES] = 1.0f / dt;
    float fps = 0;
    for (int i = 0; i < NUM_FPS_SAMPLES; i++)
        fps += fpsSamples[i];
    fps /= NUM_FPS_SAMPLES;
    return fps;
}

... as per http://www.gamedev.net/community/forums/topic.asp?topic_id=510019

Lance May
A: 

Take a look at this article about different FPS handling methods.

virious