Tuesday, November 01, 2005

Debug timing

Source Debug Timing (and a little design pattern, to boot):


In almost every bit of code I write that's actually destined to go into a real system, I find myself start to look for places to optimize code. But having read the writings of Rico Mariani, I am weary of premature optimizations. So what do we do? We measure, of course.
 
A full-fledged profiler is often overkill when I just want to check how long a method runs. Sometimes a few quick debug-printouts will do the job just fine. I've written hundreds of Debug.WriteLine("Start block") and Debug.WriteLine("End Block") statements, and it get wearisome typing the same commands, formatting the same start and end times, again and again.
 
So without further ado, he is the complete code for my little DebugTimer helper class, implemented using the Disposable Design Pattern of which I am so fond. Use it in good health.
 
public class DebugTimer : IDisposable
{
  
private DateTime start;
   private string label;
   private static int level = 0;

   public
static DebugTimer Start (string Label)
   {
      return new DebugTimer(Label);
   }

   private DebugTimer (string Label)
   {
      level++;
      this.label = Label;
      this.start = DateTime.Now;
      string message = string.Format("{2}{0}: {1}", this.label, "Starting", new string(' ', level));
      System.Diagnostics.Debug.WriteLine(message);
   }

   public void Dispose()
   {
      TimeSpan time = DateTime.Now.Subtract(
this.start);
      string message = string.Format("{2}{0}: {1}", this.label, time.ToString(), new string(' ', level));
      System.Diagnostics.Debug.WriteLine(message);
      level--;
   }
}

EDIT: I forgot to add a little usage sample here. Should be pretty clear, but just to cover all my bases:

public void SomeMethod (
   {
     
using (DebugTimer.Start("My Code Block"))
      {
         // Code to time.
      }
   }

No comments:

Post a Comment