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

Author Topic: My simple clock is acting weird  (Read 2859 times)

0 Members and 1 Guest are viewing this topic.

carton83

  • Newbie
  • *
  • Posts: 38
    • View Profile
My simple clock is acting weird
« on: January 18, 2014, 09:28:51 am »
I thought I had figured out a stupidly simple clock that runs once every "X" milliseconds, however it's not working as intended. The if statement should only run once every second but it's actually running once between every 120 ms and 110 ms. Here is a log I created. It shows how how many ms its been since the program started and what the time is once the if loop runs.

sf::Clock clocker;
short timeSinceUpdate, msUpdateTime =1000;

timeSinceUpdate += clocker.getElapsedTime().asMilliseconds();
if(timeSinceUpdate >= msUpdateTime)
{
    timeSinceUpdate = clocker.restart().asMilliseconds();
    //Code
}

carton83

  • Newbie
  • *
  • Posts: 38
    • View Profile
Re: My simple clock is acting weird
« Reply #1 on: January 18, 2014, 09:34:40 am »
Hmm, I removed my framerate limiter to get a really high resolution log (I'm not sure if that's the correct termonology but reason says it is) and the if statement runs at even shorter intervals.  Here is the log. The frame limitor was set to 120 for the previous log.

AlexAUT

  • Sr. Member
  • ****
  • Posts: 396
    • View Profile
Re: My simple clock is acting weird
« Reply #2 on: January 18, 2014, 05:13:24 pm »
Why do you use short for the time? You should use sf::Time instead

Test example:
sf::Clock time;
sf::Clock clocker;
sf::Time timeSinceUpdate = sf::Time::Zero;
sf::Time msUpdateTime = sf::milliseconds(1000);

while (time.getElapsedTime() <= sf::seconds(10))
{
        timeSinceUpdate += clocker.restart();
        if (timeSinceUpdate >= msUpdateTime)
        {
                std::cout << "Time: " << time.getElapsedTime().asMilliseconds();
                timeSinceUpdate -= msUpdateTime;
                //Code
        }
}
 

TimeSinceUpdate will only be in very rare cases exactly msUpdateTime so the next tick should consider the "overtime" of the last tick. (timeSinceUpdate -= msUpdateTime; )

For me, the code above works perfectly.


AlexAUT

 

anything