Sign in to follow this  
BrknPhoenix

Problem with this timer code?

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);
    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.

Share this post


Link to post
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 this post


Link to post
Share on other sites
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]

Share this post


Link to post
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 this post


Link to post
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;
}
}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this