Martijn Courteaux
Martijn Courteaux

Reputation: 68847

Game Development: How to limit FPS?

I'm writing a game, and I noticed the framerate is not stable. What basic logic do I need to limit the framerate of my game reliably? How do I calculate the sleep time?

I know how long it took to update the game one frame in microseconds and of course the frame rate (in frames per second (FPS)) I want to reach.

Upvotes: 13

Views: 15115

Answers (4)

virious
virious

Reputation: 571

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

UPDATE: use this link from Web Archive as original website disappeared: https://web.archive.org/web/20161202094710/http://dewitters.koonsolo.com/gameloop.html

Upvotes: 1

aioobe
aioobe

Reputation: 420921

The time you should spend on rendering one frame is 1/FPS seconds (if you're aiming for, say 10 FPS, you should spend 1/10 = 0.1 seconds on each frame). So if it took X seconds to render, you should "sleep" for 1/FPS - X seconds.

Translating that to for instance milliseconds, you get

ms_to_sleep = 1000 / FPS - elapsed_ms;

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.

Upvotes: 17

Lance
Lance

Reputation: 5800

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

Upvotes: 3

JSBձոգչ
JSBձոգչ

Reputation: 41378

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

Upvotes: 14

Related Questions