The Stopwatch Class in .NET

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 = new Stopwatch();

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

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

3 thoughts on “The Stopwatch Class in .NET

  1. You can actually make this even shorter. There is a static method on the Stopwatch class called StartNew() that returns an instance that has been started for you.


    Stopwatch myStopwatch = Stopwatch.StartNew();


    Console.WriteLine(“Do Stuff took {0} ms”, myStopwatch.ElapsedMilliseconds);

    I’ve got a class called a StopwatchWriter that simplifies everything if you’re profiling multiple parts of the same method as well.

  2. Thanks for the comment. I didn’t know about the static method.

    I do a similar thing by deriving from the Stopwatch and logging the elapsed time in the Dispose. I was going to blog about that next, but I guess you beat me to it ;)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>