Often time you need a quick way to time a function or block of code, in early version of .NET you had to write some cumbersome code that relied on the DateTime object. With the introduction of the Stopwatch (.NET 2.0) things got better but still, it took lots of code to insert a simple timing logic:

Insert Declare, initialize and start statements before the code block to time.
Stop and display results after the code block.

Old way:

      string message = "Calculate 800K square roots";
      int roots = 800000;
      System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
      System.Diagnostics.Trace.WriteLine(string.Format("{0}: {1} (seconds)", 
                                       message, sw.Elapsed.TotalSeconds)); 

Better way:

      using (QuickStopwatch qsw = new QuickStopwatch(message))

CalcRoots is a 'slow' runnig function we want to time:
   private static double  CalcRoots(int rootsCount)
      double sum = 0;
      for (int i = 0; i < rootsCount; i++)
        sum += Math.Sqrt(i);
      return sum;

QuickStopwatch pattern offers far less code pollution. The QuickStopwatch class is lightweight and most of its content is stripped in release mode.

Last edited Aug 2, 2012 at 2:26 AM by AmirLiberman, version 1


No comments yet.