With .NET 2.0 they introduced the StopWatch class which can be used to time the execution of your code to a very high resolution. Here is a wrapper to help package it up.
public class PerformanceTimer : IDisposable
{
Stopwatch _stopwatch = new Stopwatch();
private static string _elapstedTime;
public PerformanceTimer()
{
PerformanceTimer._elapstedTime = string.Empty;
_stopwatch.Start();
}
public static string ElapstedTime
{
get { return _elapstedTime; }
set { _elapstedTime = value; }
}
public void Dispose()
{
_stopwatch.Stop();
TimeSpan ts = _stopwatch.Elapsed;
_elapstedTime =
String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
}
}
The class is used in the following manner:
using(new PerformanceTimer())
{
//Execute code you are timing here.
}
string result = PerformanceTimer.ElapstedTime;