Wednesday, December 29, 2010

Clocking your code with a stopwatch

Sometimes when you want to find out which part of your code is taking a long time to run, you can wrap sections of your code with a Stopwatch like so:

#if DEBUG
  System.Diagnostics.Stopwatch clock =
    System.Diagnostics.Stopwatch.StartNew();  
#endif

//put your long running code here

#if DEBUG
  clock.Stop();
  System.Diagnostics.Debug.WriteLine(string.Format(
    "Time to do ACTIVITY: {0} sec",clock.ElapsedMilliseconds/1000.0));
#endif

Now when you run your application in debug mode, your timing reports will be written to the output screen. If you happen to release your application with this code still there, it does not affect the performance of your application at all because the #if DEBUG directives tell the compiler to only pay attention to the enclosed segments of code when you are debugging.

No comments: