Weird timing issue with Thread.sleep

Andrej Mitrovic andrej.mitrovich at gmail.com
Wed Aug 3 11:36:21 PDT 2011


On 8/3/11, Jacob Carlborg <doob at me.com> wrote:
> Why would you want to slow down framerate?

Because the examples were written in the 90s and CPUs and graphic
cards are so fast these days that the old code runs at an enormous
framerate.

Anyway, after a bit of googling I've found a solution:

enum float FPS = 60.0;
auto t_prev = Clock.currSystemTick();
while (!done)
{
    auto t = Clock.currSystemTick();

    if ((t - t_prev).usecs > (1_000_000.0 / FPS))
    {
        t_prev = t;
        DrawGLScene();
    }

    SwapBuffers(hDC);
}

I can also use currAppTick() which is similar.

I'm using "enum float" instead of just "enum FPS" because creeping
integer truncation bugs lurk into my code all the time. i.e. I end up
having an expression like "var1 / var" evaluate to an integer instead
of a float because a variable was declared as an integer.

Here's what I mean:
enum FPS = 60;

void main()
{
    auto fraction = (1 / FPS);  // woops, actually returns 0
}

Using "enum float FPS = 60;" fixes this. It's a very subtle thing and
easily introducable as a bug.


More information about the Digitalmars-d-learn mailing list