Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: sf::Clock::Restart() is inconsistent  (Read 3430 times)

0 Members and 1 Guest are viewing this topic.

Kai

  • Guest
sf::Clock::Restart() is inconsistent
« on: February 08, 2012, 01:05:40 am »
Hey all I wanted to share an issue I have discovered in SFML 2 regarding sf::Clock timing. My goal is to be able to measure how much time has elapsed since the last time the main game loop was run, and accumulate that amount toward a main game timer variable.

Here is Method 1, taking advantage of clock.Restart():

Code: [Select]

sf::Clock clock;
int gameTime = 0;
while (true) {
  int elapsed = clock.Restart().AsMilliseconds();
  gameTime += elapsed;

  // do stuff...
}


Here is Method 2, which uses an extra variable to keep track of the previous loop time:

Code: [Select]

sf::Clock clock;
int gameTime = 0;
int prevTime = 0;
while (true) {
  int time = clock.GetElapsedTime().AsMilliseconds();
  int elapsed = time - prevTime;
  prevTime = time;
  gameTime += elapsed;

  // do stuff...
}


It is my belief that Method 1 is just an SFML shortcut for Method 2 and so these should result in the same timings. However, I have found that's not the case. Method 1 runs slower than Method 2, and seems to be off by milliseconds for each loop.

Am I understanding the usage improperly, or is this a problem with SFML 2?

Laurent

  • Administrator
  • Hero Member
  • *****
  • Posts: 32504
    • View Profile
    • SFML's website
    • Email
sf::Clock::Restart() is inconsistent
« Reply #1 on: February 08, 2012, 08:10:14 am »
These codes are not equivalent at all. The first one measures very tiny durations and adds them together, so precision errors accumulates very quicky. The second one runs a single clock that is never reset, it always returns the right time so any precision error that would happen in one frame is corrected in the next one.

The equivalent for
Code: [Select]
elapsed = clock.Restart();
is
Code: [Select]
elapsed = clock.GetElapsedTime();
clock.Restart();


I suggest that you stick to your second solution (ie. not resetting the clock every frame) ;)
Laurent Gomila - SFML developer

Kai

  • Guest
sf::Clock::Restart() is inconsistent
« Reply #2 on: February 08, 2012, 04:36:34 pm »
Thanks! I figured I was misunderstanding, but I wanted to be sure.