Let’s say you want to time how long something takes to run. Well, before .NET 2.0, maybe you capture the start time and end time – and then try to fumble through some way to calculate the elapsed time. Then in .NET 2.0 – maybe it got one step better because you could calculate a “TimeSpan” from the two times. Well, there is one step better – it’s System.Diagnostics.Stopwatch. For example:
Stopwatch currentStopwatch = new Stopwatch();
currentStopwatch.Start();
// execute some code
currentStopwatch.Stop();
MessageBox.Show(currentStopwatch.Elapsed.ToString());
That outputs a very high resolution output, for example:
00:00:00.0000117
In a pinch, if you don’t have a better way to instrument or profile code – this makes it a little easier.
Leave a Reply