Simple Helper class to Profile methods in C#

Posted by craig Monday, May 04, 2009 11:46:40 AM

 

Profiling a method in C# is a bit tricky because we need to take into account the precompilation overhead the first time the method is executed.  For performance sensitive applications it can be useful to have a simple helper class /method to do the repeated work of executing the method once and then averaging the times.

The simple helper method GetMilliSecsTime should be enough to do the trick.  It takes the number of repetitions and an Action delegate which encapsulates the method being profiled.

  /// <summary>
  /// helper class for profiling
  /// </summary>
public static class ProfileHelper
  {

    /// <summary>
    /// gets the time Now
    /// </summary>
    /// <value>The value of the time Now</value>
    static DateTime Now
    {
      get
      {
        return DateTime.Now;
      }
    }
  /// <summary>
  /// gets the number of millisecs required to execute the task
  /// we compute this by averaging over numRepetitions.
  /// NOTE:  the task is executed once to overcome the effects of profiling
    /// </summary>
    /// <param name="numRepetitions">The num repetitions.</param>
    /// <param name="task">The task.</param>
    /// <returns></returns>
  public static int GetMilliSecsTime(int numRepetitions,Action task)
  {
    //make sure to exclude precompiling by executing the task once before we profile!
    task();
    DateTime start = Now;
    for (int i = 0; i < numRepetitions; i++)
    {
      task();
    }
    return Now.Subtract(start).Milliseconds/numRepetitions;
  }

  }

Copyright 2009 AnyTime
Comments are closed on this post.