As part of the samples included in my last presentation
about .NET Performance and Scalability, there is a useful
class that encapsulates the Win32 functions
QueryPerformanceCounterand
QueryPerformanceFrequency. These functions let you measure the performance of your
code to nanosecond accuracy (10-9 sec). However,
after all internal and
interop
cross-boundary calls, you get 10 us (10-6 sec)
that is an order of magnitude better that the 10
milliseconds resolution of the managed DateTime class.Note: This class (Stopwatch) resembles (same interface
definition) the one in the .NET Framework 2.0 (Whidbey) that
you will found on the System.Diagnostics namesapece. The
good thing is that you can use this class with .NET
Framework v1.1 and you will have full compatibility when
v2.0 comes up.DownloadsYou can download the code from
here.UsageIts usage is very straightforward.Stopwatch myTimer =
new Stopwatch();
myTimer.Start();
// Do some stuff here
myTimer.Stop();// Show Resultsdouble
result = myTimer.Elapsed.TotalMilliseconds;Console.WriteLine( "Elapsed milliseconds: {0}", result
);// If you want a new timing, just reset the current
timermyTimer.Reset();