Measure code performance using an Action in .Net

One of my favorite duties at work is performing code reviews, I find the process instrumental in identifying opportunities for improvements regardless of the team / organization size or its available skill sets.

There is an abundance of reasons to start performing code reviews and none to prevent.

Reasons to perform code reviews are:

  1. Code Quality, reviewers ensure quality of code committed.
  2. Mentoring, code reviews are the best to tool to help team identify developers' areas of improvements.
  3. Team familiarity, teams will know each others strengths and know where to go and who to ask for help.
  4. Defect rate reduction, chances of having defects in reviewed code are much smaller than in unreviewed code (we all make mistakes).

Smart bear Software have written an excellent & free book on code reviews, you can see it Here

Today, I wanted to measure the performance of some Parallel function submitted by one of our developers and found myself writing this Action. The action takes another action as a parameter, runs it while writing the performance measures to Visual Studio.Net output window

public static Action<Action> PerformanceCalculator = ((action) =>
    var watch = new Stopwatch();
    Debug.Write(string.Format("Started Stopwach at {0} ", DateTime.Now), action.Method.Name);
    Debug.Write(string.Format("Stopped Stopwach at {0} ", DateTime.Now), action.Method.Name);
    Debug.Write(string.Format("Total execution time in TotalMilliseconds is {0} ", watch.Elapsed.TotalMilliseconds), action.Method.Name);

The last Debug.Write call will contain the method's total time consumption in milliseconds. That's it, short and sweet. You utilize this to measure performance of any C# call.


Comments (4) -

Thanks for the book reference Sammy. Code reviews is something we are guilty of neglecting.

Don't you guys use any performance profilers?

I was thinking of creating something similar

Our profiler of choice is Ants Profiler, However, I don't think firing a profiler to measure a single function time consumption isn't a wise decision as far as time management.

Comments are closed