Monday, March 16, 2009

Generic timing method to profile execution time of your methods

While using a profiler is a great way to time the execution (as well as memory) for method executions in your code, I thought I would like to have some generic way to time the executions of my methods.

The end result is pretty simple but may not be the best way to do it. Definitely not as generic as I wanted it to be. But this would work for some performance testing of algorithms.

The code for the TimeAndExecute() method is shown below.

   1: /// <summary>

   2: /// This method executes the action passed and then returns the total time

   3: /// taken in milliseconds using Stopwatch.

   4: /// </summary>

   5: /// <param name="action">the action to be performed</param>

   6: /// <returns>time elapsed in milliseconds</returns>

   7: public static double TimeAndExecute(Action action)

   8: {

   9:     Stopwatch sw = Stopwatch.StartNew();

  10:     action();

  11:     sw.Stop();

  12:     return sw.ElapsedMilliseconds;

  13: }

The usage is also simple.

   1: static void Main(string[] args)

   2: {

   3:     //usage.

   4:     var timetaken = TimeAndExecute(() =>

   5:                        {

   6:                            Console.WriteLine("Test");

   7:                        });

   8:     Console.WriteLine(timetaken);

   9: }

Pretty simple huh!

No comments: