Measure Memory Usage of .NET Applications

There are two main methods for measuring the memory usage of a .NET application, using the GC class or using System.Diagnostics

Retrieve Your App’s Memory Utilization using the GC class

The .NET Framework’s GC class contains many useful memory-related methods, including GetTotalMemory(), which returns the amount of memory the garbage collector believes is allocated to your app. The number not be exact right since some objects may not have been garbage collected yet. This, however does have the advantage of being able to inform you of the amount of memory a certain part of your app uses, as opposed to the entire process:

long memAvailable = GC.GetTotalMemory(false);
Console.WriteLine(“Before allocations: {0:N0}”, memAvailable);

int allocSizeObj = 40000000;
byte[] bigArrayObj = new byte[allocSizeObj];

memAvailable= GC.GetTotalMemory(false);
Console.WriteLine(“After allocations: {0:N0}”, memAvailable);

The above code will output the following:

Before allocations: 651,064
After allocations: 40,690,080

Retrieve Your App’s Memory Utilization using System.Diagnostics

You can also request the OS report on info about your process using the Process class  in the System.Diagnostics namespace:

Process procObj = Process.GetCurrentProcess();
Console.WriteLine(“Process Info: “+Environment.NewLine+
“App's Private Memory Size : {0:N0}”+Environment.NewLine +
“App's Virtual Memory Size : {1:N0}” + Environment.NewLine +
“App's Working Set Size: {2:N0}” + Environment.NewLine +
“App's Paged Memory Size: {3:N0}” + Environment.NewLine +
“App's Paged System Memory Size: {4:N0}” + Environment.NewLine +
“App's Non-paged System Memory Size: {5:N0}” + Environment.NewLine,
procObj.NonpagedSystemMemorySize64 );

Here’s the output:

Process Info:
Private Memory Size: 75,935,744
Virtual Memory Size: 590,348,288
Working Set Size: 29,364,224
Paged Memory Size: 75,935,744
Paged System Memory Size: 317,152
Non-paged System Memory Size: 37,388

These numbers are not necessarily intuitive, and you can consult a good operating system book, such as Windows Internals from Microsoft Press for more on how virtual memory works. Performance counters can also be used to track this as well as other info on your app or its environment.

Twitter Digg Delicious Stumbleupon Technorati Facebook Email

No comments yet... Be the first to leave a reply!