Monday, April 20, 2009

QueryPerformanceTimer

Whenever I try to use a high resolution timer,
I have written source codes down everytime.

This post is to save it. Back up. :)


#include windows.h

class QueryPerformanceTimer
{
public:
QueryPerformanceTimer() : timer_frequency_(0)
{
init();
}
virtual ~QueryPerformanceTimer() {;}

void init()
{
if (QueryPerformanceFrequency(&frequency_))
{
//printf("High:%d, Quad:%d, Low:%d\n", frequency_.HighPart, frequency_.QuadPart, frequency_.LowPart);
timer_frequency_ = (double)((long double)(frequency_.HighPart >> 32) + frequency_.LowPart);
}
else
printf("QueryPerformanceFrequency returned FAIL\n");
}

void start()
{
if (timer_frequency_ == 0)
return;

QueryPerformanceCounter(&initial_);
}

void stop()
{
if (timer_frequency_ == 0)
return;

QueryPerformanceCounter(&counter_);
}

double elapsed()
{
if (timer_frequency_ == 0)
return 0;

double elapsed = (double)((long double)(counter_.QuadPart - initial_.QuadPart) / (long double)frequency_.QuadPart);
return elapsed;
}

bool is_valid()
{
return timer_frequency_ != 0;
}

double timer_frequency()
{
return timer_frequency_;
}

private:
LARGE_INTEGER initial_;
LARGE_INTEGER frequency_;
LARGE_INTEGER counter_;

double timer_frequency_;
};


This code is very weak against exceptions. But it's okay if you use it simply.
Copy & Paste!!!

No comments:

Post a Comment