Stopwatch in .NET

.NET provides plenty of ways for delaying the execution using timers. But many programmers keep thinking of getting a way out to know the time required to execute a code in the application. How do we do this?

The conventional way to do this is to do something like the following snippet:

  1. int startTime = System.DateTime.Now.Millisecond;  
  2. //Code to be evaluated  
  3. int stopTime = System.DateTime.Now.Millisecond;  
  4. int difference = stopTime - startTime;  
But fortunately, .NET provides the Stopwatch Class, in the namespace System.Diagnostics that allows us to accurately measure elapsed time in a software application. This is cleaner and reliable. A Stopwatch instance can measure elapsed time over several intervals with the total elapsed time calculated by adding all of the intervals together.

The difference in time is available as a TimeSpan and is formatted as d.hh:mm:ss.ff:

 

  • d = days
  • hh = hours
  • mm = minutes
  • ss = seconds
  • ff = fractions of a second

The following is an example of using StopWatch Class to get the time elapsed instead of the above method.

  1. using System.Diagnostics; //namespace  
  2.   
  3. Stopwatch stopWatchObj = new Stopwatch();  
  4. stopWatchObj.Start();  
  5. // Code to be evaluated  
  6. stopWatch.Stop();  
  7. TimeSpan ts = stopWatch.Elapsed;  
I hope this blog helps in understanding the most convenient way to get the time required to execute a code snippet and helps in making more reliable applications.

Happy Coding.

 

Ebook Download
View all
Learn
View all