.NET logo

high precision stopwatch

home | software | utility classes | high precision stopwatch

using the class

An example usage, showing a simple case:

IStopWatch stopWatch = new PrecisionStopWatch(); stopWatch.Start(); // ...perform task to be timed... TimeSpan elapsed = stopWatch.Time;

The IStopWatch interface supports these methods and properties:

Calling Stop and Reset is optional, and facilitates using the one stopwatch to measure the sum of several periods of time. The behaviour is intended to model that of a standard stopwatch. Calling Reset while the stopwatch is running will return the count to zero, and keep the clock running.

how it works

Both PrecisionStopWatch and StopWatch classes provide the same interface, and similar behaviour. StopWatch compares values from the system call DateTime.Now, which results in time measurements with a resolution of 15ms (on average) due to the nature of the managed environment. In many cases, this will suffice. However, when a finer resolution is required, the PrecisionStopWatch should be used. It uses Win32 Interop calls to kernel32.dll to achieve sub-millisecond precision.

.NET 2.0

Note that since publishing this article the .NET framework has included a class to measure time more accurately. Versions 2.0 and later include the class System.Diagnostics.Stopwatch which achieves the same result via the same underlying Win32 calls, though with a subtly different interface.

Stopwatch stopwatch = Stopwatch.StartNew(); // ...perform task to be timed... TimeSpan elapsed = stopwatch.Elapsed;


submitting feedback

Please feel free to provide feedback on this class . Bug reports are most appreciated when accompanied by a failing NUnit test case.