The Stopwatch Class in .NET 2.0


 

Do you ever find yourself using DateTime to time a section of code?  If you do, you should look at the System.Diagnostics.Stopwatch class that was introduced in the 2.0 framework.

  Stopwatch stopwatch = new Stopwatch();
  stopwatch.Start();

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

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

The Stopwatch measures elapsed time by counting timer ticks in the underlying timer mechanism. If the installed hardware and operating system support a high-resolution performance counter, then the Stopwatch class uses that counter to measure elapsed time. Otherwise, the Stopwatch class uses the system timer to measure elapsed time. Use the Frequency and IsHighResolution fields to determine the precision and resolution of the Stopwatch timing implementation.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s