#668 – GetTotalMemory Indicates How Much Memory You’ve Allocated
September 11, 2012 2 Comments
You can call the GC.GetTotalMemory function to find out the total # bytes you’ve allocated so far on the managed heap. Note that this number does not include other memory that your process may have allocated, including things like memory allocated in unmanaged code.
static void Main() { try { #if DEBUG GC.Collect(); #endif Console.WriteLine(string.Format("Before we start, total mem alloc'd {0} bytes", GC.GetTotalMemory(false))); while (true) { ConsoleKeyInfo cki = Console.ReadKey(); int size = 1024 * 1024 * 100; // 100MB byte[] data = new byte[size]; Array.Clear(data, 0, size); _bigList.Add(data); #if DEBUG GC.Collect(); #endif Console.WriteLine(string.Format("Total mem alloc'd now {0} bytes", GC.GetTotalMemory(false))); } } catch (Exception xx) { Console.WriteLine(xx.ToString()); Console.ReadLine(); } }
The comment should be “// 100MB”.
Thanks David. Corrected. Technically, Mebibyte rather than Megabyte. But no self-respecting software developer would stoop low enough to nit-pick decimal vs. binary version of MB.