14th Jan, 2008

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();
  stopwatch.Start();

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

  stopwatch.Stop();
  Console.WriteLine( "This process took {0} ms",
    stopwatch.ElapsedMilliseconds );
If you found this post helpful, please "Kick" it so others can find it too:

Responses

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.

ex.

Stopwatch myStopwatch = Stopwatch.StartNew();

DoStuff()

myStopwatch.Stop();
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.

http://www.vonsharp.net/StopwatchWriterClass.aspx

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 ;)

This has been around for 3 years now, and I’ve never known about it. Thanks!

you love this? [URL=http://burberrytrenchcoat.devhub.com/]burberry trench coat[/URL] with low price dugWaapS [URL=http://burberrytrenchcoat.devhub.com/ ] http://burberrytrenchcoat.devhub.com/ [/URL]

Leave a response

Your response: