Windows API Timer with microsecond (or better)
accuracy.
by Curtis Krauskopf
Q: I need a timer timer with a 1 microsecond
(1,000,000th of a second) accuracy.
A: You need to use the high resolution
performance counter that is available in the QueryPerformanceCounter()
function. It is able to provide times that exceed
1 microsecond accuracy on most hardware.
The availability of the QueryPerformanceCounter()
is dependent.on the system's hardware. To find
out if it's available, and to find out its accuracy,
use the QueryPerformanceFrequency() function.
The QueryPerformanceCounter() function
returns the amount of time that has elapsed since the
system was booted. Elapsed time can be found by
comparing the returned values at two different points
in time.
Here's an example of getting the amount of time since
the system has started:
#include <windows.h> #include <stdio.h>
...
...
LARGE_INTEGER ticksPerSecond;
LARGE_INTEGER tick; // A point in time
LARGE_INTEGER time; // For converting tick into real time
// get the high resolution counter's accuracy
QueryPerformanceFrequency(&ticksPerSecond);
// what time is it?
QueryPerformanceCounter(&tick);
// convert the tick number into the number of seconds
// since the system was started...
time.QuadPart = tick.QuadPart/ticksPerSecond.QuadPart;
//get the number of hours
int hours = time.QuadPart/3600;
//get the number of minutes
time.QuadPart = time.QuadPart - (hours * 3600);
int minutes = time.QuadPart/60;
//get the number of seconds
int seconds = time.QuadPart - (minutes * 60);
AnsiString result = "The system was started ";
result += IntToStr(hours) + " hours ";
result += IntToStr(minutes) + " minutes ";
result += IntToStr(seconds) + " and ";
result += AnsiString(tick.QuadPart % ticksPerSecond.QuadPart);
result += AnsiString("/") + ticksPerSecond.QuadPart;
result += " seconds ago.";
printf("%s", result.c_str());
|
Ignore the Conversion may lose significant digits
warnings when compiling this sample. The compiler
doesn't know that most computers are not on for 2 billion
hours (0x7FFFFFFF) without being rebooted!
This
article was written by Curtis Krauskopf (email at ).
Popular C++ topics at The Database Managers:
The Database Managers
helps companies to:- become more profitable
- grow their
business
- fix programs
that are behaving badly
- write new programs
to solve business problems
- do more with
fewer resources
Email them at
to find out how to make your company more successful.
|
|