Poor developer’s performance profiler

In the last post I wrote about a simple method that can help .NET developers micro measure the memory consumption of their application, in this post I want to show a way to measure application performance.

imageBefore I start I want to state here and now that there is no substitute to using an actual profiling application that will can find performance bottlenecks and problematic code, but if you have a small piece of code that needs profiling or you have a good idea where your problems lie then keep on reading.

For performance measuring I’m going to use old trusty System.Diagnostics.StopWatch I’ve Already talked about before. The main difference between measuring memory and performance is that when measuring performance I want to be able to know the amount of time a method inside a process took as well as the time of the whole action, in other words I need to have nested watches. Don’t worry, it’s easy.

In this solution I use three classes (no including Stopwatch):

The Code

A simple logger representation:


The manager class that spawns new stoppers each time Start is called:


And finally  the StopperLogger (I’m awful with names) class – this is where the magic happens:


Each time that this class is created the current elapsed time is saved and when this class get’s disposed it uses the logger to write how much time has passed.

How to use stopper

The code that uses these classes will look something along these lines:


Running the code will write three entries in the log (or console in this case):

  1. How many milliseconds running RunPhaseOne takes
  2. How many milliseconds running RunPhaseTwo takes
  3. How much time running the whole method takes


Again I’d like to remind you that this method is good for small code snippets and cannot replace a profiling application. But if you know what part of your code to optimize or if need to add performance logging to your code so you can check how much time it take it to run on your customer machine, these classes can save you time.


Related posts:

Labels: ,