Articles

Navigation ( archives ›› 2006 ›› December ›› 21 ›› High Resolution Timer in NET 2.0 )

High Resolution Timer in NET 2.0

Posted on December 21, 2006, 9:11 pm EST

The Classic

Windows Forms Timer in .NET 2.0 is a bit slow, one may want to use the highest resolution timer the system has. This library will use the fastest Windows Timer by interoping the Kernel32.dll inorder to access the QueryPerfomanceCounter.

Comparisons between existing timers

CODE:
Function                 Units                      Resolution
---------------------------------------------------------------------------
Now, Time, Timer         seconds                    1 second
GetTickCount             milliseconds               approx. 10 ms
TimeGetTime              milliseconds               approx. 10 ms
QueryPerformanceCounter  QueryPerformanceFrequency  same

The QueryPerformanceCounter function returns the current value of the high-resolution performance counter. The current Windows Forms Timer, returns a 1 second resolution, in many cases that may be enough. When timing is a must, using the QueryPerformanceFrequency is the best in its class.

How to use

Import the namespace

CODE:using HighResolutionTimer;

We need to create an instance of the HighResolutionTimer

CODE:SystemTimer timer = new SystemTimer();

Then if you wish to time a method or anything else you coudl do the following

CODE:
// Start the Timer
timer.Start();

// Lets do some stuff
int i;
for (i=0;i<1000;i++) 
{
 Console.Write(i + "|");
}

// Stop the Timer
timer.Stop();

Console.WriteLine("Duration: {0}",timer.Duration);

Download

The Library: here

The Source Code: here

References

About this Article:

Comments (0) - Add yours, or View the replies

Categoy (CSharp)

Views (2707)

Digg it: Digg this article