The Stopwatch Class in .NET

2008, Jan 14    

Do you ever find yourself using DateTime to time a section of code?  Do you have code like the following?

DateTime start = DateTime.Now;

// Perform a long process
Thread.Sleep( 1968 );

DateTime end = DateTime.Now;
TimeSpan duration = end.Subtract( start );
Console.WriteLine( "This process took {0} ms", duration.TotalMilliseconds );

If you do, you should look at the System.Diagnostics.Stopwatch class that was introduced in the 2.0 framework.  You can convert the code above to the much more readable

Stopwatch stopwatch = Stopwatch.StartNew();

// Perform a long process
Thread.Sleep( 1968 );

stopwatch.Stop();
Console.WriteLine( "This process took {0} ms", stopwatch.ElapsedMilliseconds );