leaflet757
leaflet757

Reputation: 159

Only Evaluates as True when Thread Sleeps

I am getting some unexpected behavior I don't understand. I am trying to implement a fixed variable time step as described from http://gafferongames.com/game-physics/fix-your-timestep/ and http://gameprogrammingpatterns.com/game-loop.html. My inner while loop never evaluates as true when I run the program in visual studio; however, when I uncomment 'this_thread::sleep_for(1s)', the while loop will evaluate as a true after the outer loop executes 10 times or so. I would expect on faster machines, this would be the expected outcome.

So my question is why would the inner loop only evaluate as true when the 'this_thread::sleep_for(1s)' is uncommented? Shouldn't lagTime become greater than fixedDeltaTime regardless of the sleep_for? Does the math take too much time for the computer or something?

int updateCount = 0;

double CLOCKS_PER_MILLISECOND((double)CLOCKS_PER_SEC * 1000.0);
double previousTime = std::clock() / CLOCKS_PER_MILLISECOND;
double newTime = 0, deltaTime = 0, lagTime = 0;
double fixedDeltaTime = 1.0 / 60.0;

while (gameIsRunning)
{
    newTime = std::clock() / CLOCKS_PER_MILLISECOND;
    deltaTime = newTime - previousTime;
    previousTime = newTime;
    lagTime += deltaTime;

    inputSystem.update();
    sceneManager.update();

    while(lagTime >= fixedDeltaTime) // never evalutes as true?
    {
        physicsSystem.update();

        lagTime -= fixedDeltaTime;

        updateCount++;
    }

    std::cerr << "-----" << updateCount << "-----" << std::endl;

    physicsSystem.interpolate(lagTime / fixedDeltaTime);

    renderSystem.update();
    audioSystem.update();

    updateCount = 0;
    //std::this_thread::sleep_for(1s);
}

Thank you for any help!

Upvotes: 0

Views: 45

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

You're trying to measure time using clock(), but that is a process tick counter that won't advance while all threads in your process are sleeping. The whole point of sleep is to tell the CPU "don't give this process any attention for a while!". As far as your program is concerned, time freezes while it's asleep.

If you waited long enough, lagTime would eventually advance past fixedDeltaTime because the period of time during which your program is not sleeping consumes ticks ... but you'd have to wait for many, many seconds.

Don't use clock() to measure the absolute passage of time.

Upvotes: 2

Related Questions