Problem with this timer code?

Started by
5 comments, last by BrknPhoenix 17 years, 6 months ago
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);
    Then = (HighResTimer.QuadPart / TimerFrequency.QuadPart) / 1000;
}

void MillisecondsTimer::CountMilliseconds()
{   
    QueryPerformanceFrequency(&TimerFrequency);
    QueryPerformanceCounter(&HighResTimer);
    
    Now = (HighResTimer.QuadPart / TimerFrequency.QuadPart) / 1000;

    if ((Now - Then) > 1)
    {
        Milliclock++;
        Then = Now;
    }        
}
The problem is that the "if ((Now - Then) > 1)" condition always evaluates false.
Advertisement
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?
And what, we're supposed to guess how it doesnt quite work?

in other words, what's the problem?

[edit] nevermind, sorry, i didnt see your ingeniously hidden last line there :/ [/edit]
[size=2]aliak.net
Your formula is wrong. It should look like this:

time_in_msec = ((HighResTimer.QuadPart*1000) / TimerFrequency.QuadPart);
You also only have to call QueryPerformanceFrequency once at the beginning of the code do get the frequency of the timer.
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.
We''re sorry, but you don''t have the clearance to read this post. Please exit your browser at this time. (Code 23)
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;    }       }

This topic is closed to new replies.

Advertisement