Poor developer’s memory profiler

Some tools save you money.

The rule of the thumb is that if you save X days using the tool and your salary is Y dollars (or whatever you get paid with) per day then the tool is worth X times Y - it’s that simple.3D Bar Graph Meeting by lumaxart.

Over the years I’ve used several tools to do performance profiling but I’ve never quite found a good memory profiler.

Although there are some solid and effective memory profilers for .NET - they tend to run forever and the results they supply are less than optimal, using a memory profiler I could find out the type of the object that took most memory but could not find where the memory “hot spot” is (where the offending memory was allocated).

Last week while waiting for the memory profiler was taking a “snapshot” (it took two hours before I terminated it) we found a simpler way to tackle our problem, and it’s called System.GC.GetTotalMemory.

Oddly enough that method does exactly what you’d expect – return the amount of the allocated managed memory and is easy to use.

At the beginning of the code we want to measure we store the current allocated memory by calling:

long initialMemory =  System.GC.GetTotalMemory(true);

After that whenever we want to know the memory difference all we need to do is call the method again and subtract the returned value from the initial memory allocated:

long currentMemory =  System.GC.GetTotalMemory(true);

var memoryAllocated = currentMemory – initialMemory;

The parameter passed to the call tells the method to initiate garbage collection before calculating the memory size and it might cause a small delay. There is a small gotcha – using this system with multithreaded code can cause weird results but so far I haven’t noticed any.

GetTotalMemory is very useful but don’t forget that it’s not a fully fledged profiler and should only be used for profiling a small part of your code – using it to profile an entire application would be more difficult.

Labels: ,