Stopwatch

Thu, December 16, 2004, 01:03 PM under MobileAndEmbedded
A useful class in .NET 2.0 for measuring performance, but not only, is the System.Diagnostics.Stopwatch class. Once again this does not appear to be part of CF 2.0, so I set out to implement one for both CF 1.0 and desktop version today (.NET 1.1) and tomorrow (CF 2.0).

You can download the dll from here (so you get the BackgroundWorker as a bonus) or get the code at the end of this entry.

The interface is very simple:
1. Create an instance of a Stopwatch class.
2. Start it and stop it at will, or reset it back to zero.
3. At any moment in time, access one of its Elapsed properties (returning TimeSpan, milliseconds or ticks)
4. You can check if an instance is running

There are also a bunch of static (Shared in VB) calls you can make:
5. If you are lazy and want a new already started Stopwatch with one call, use the StartNew static method
6. If you just want to know the current number of ticks in the timer mechanism, call the static GetTimeStamp
7. The number of ticks per second is accessible via another static: Frequency

Cannot get much simpler, can it :-) In addition, on MSDN you can find: .NET Client Stopwatch Application Sample

My implementation uses the high resolution QueryPerformanceCounter/Frequency APIs. If they are not supported on your device, you will get an exception when creating a Stopwatch [note that the .NET 2.0 version copes with a fallback mechanism, I have not implemented that]. If you are the unfortunate owner of such a device then I suggest you use Environment.TickCount.

Download the DLL here
Download the VB code here
Download the C# code from OpenNETCF