• 13
• 18
• 19
• 27
• 9

# Problem with this timer code?

This topic is 4165 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hey, this is a constructor and a function I made that is supposed to work as a milliseconds counter, but it doesn't quite work! Any help would be greatly appreciated :)
MillisecondsTimer::MillisecondsTimer()
{
Milliclock = 0;
QueryPerformanceFrequency(&TimerFrequency);
QueryPerformanceCounter(&HighResTimer);
}

void MillisecondsTimer::CountMilliseconds()
{
QueryPerformanceFrequency(&TimerFrequency);
QueryPerformanceCounter(&HighResTimer);

if ((Now - Then) > 1)
{
Milliclock++;
Then = Now;
}
}

The problem is that the "if ((Now - Then) > 1)" condition always evaluates false.

##### Share on other sites
I've got some problems too, check my thread:
http://www.gamedev.net/community/forums/topic.asp?topic_id=420586

Do you got a dual-core cpu?

##### Share on other sites
And what, we're supposed to guess how it doesnt quite work?

in other words, what's the problem?

 nevermind, sorry, i didnt see your ingeniously hidden last line there :/ [/edit]

##### Share on other sites
Your formula is wrong. It should look like this:

##### Share on other sites
You also only have to call QueryPerformanceFrequency once at the beginning of the code do get the frequency of the timer.

##### Share on other sites
It's been some time since I've done Windows programming, but if I remember correctly, the time you're getting back is milliseconds as an integer. You divide it by 1000, also as an integer, and you get a value with a resolution of a second.

This means that (now - then) is probably less than one second, but at a one second resolution, you get zero.

You should cast it as a float and divide by 1000.0f. Really though, if you just want to make sure that time has pass, there's no reason to divide both numbers twice each and then compare them. Get the difference, make sure it's non-zero, and then do whatever you need to with that number.

##### Share on other sites
Got it, thanks for the help!

The winning solution was...

#define ConvertCyclesToMilliseconds()  ((HighResTimer.QuadPart / (double)TimerFrequency.QuadPart) * 1000)MillisecondsTimer::MillisecondsTimer(){    Milliclock = 0;    QueryPerformanceFrequency(&TimerFrequency);    QueryPerformanceCounter(&HighResTimer);    Then = ConvertCyclesToMilliseconds();}void MillisecondsTimer::CountMilliseconds(){       QueryPerformanceCounter(&HighResTimer);        Now = ConvertCyclesToMilliseconds();    if ((Now - Then) >= 1)    {        Milliclock += (TimerValue)(Now - Then);        Then = Now;    }       }