Sep 24, 2015

Stopwatch in .NET

The conventional way to do this is to do something like


     int startTime = System.DateTime.Now.Millisecond;
    //Code to be evaluated
    int stopTime = System.DateTime.Now.Millisecond;
    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.


    using System.Diagnostics; //namespace 
     
    Stopwatch stopWatchObj = new Stopwatch(); 
    stopWatchObj.Start(); 
    // Code to be evaluated 
    stopWatch.Stop(); 
    TimeSpan ts = stopWatch.Elapsed;  

No comments:

Post a Comment