How to get the Memory Used by a Delphi Program

lkessler picture lkessler · Jan 13, 2009 · Viewed 33.3k times · Source

I know how to get the System memory use using GlobalMemoryStatusEx, but that tells me the what the entire OS is using.

I really want my program to report how much memory it alone has allocated and is using.

Is there any way within my Delphi 2009 program to call either a Windows function or maybe some FastMM function to find out the memory that has been allocated by my program alone?


Revisiting my question, I have now changed my accepted answer to the GetMemoryManagerState answer by @apenwarr. It produced identical results to the GetHeapStatus function (now deprecated) that I used to use, whereas GetProcessMemoryInfo.WorkingSetSize gave a very different result.

Answer

apenwarr picture apenwarr · Feb 17, 2009

You can get useful memory usage information out of the Delphi runtime without using any direct Win32 calls:

unit X;

uses  FastMM4; //include this or method will return 0.
....

function GetMemoryUsed: UInt64;
var
  st: TMemoryManagerState;
  sb: TSmallBlockTypeState;
begin
  GetMemoryManagerState(st);
  result :=  st.TotalAllocatedMediumBlockSize
           + st.TotalAllocatedLargeBlockSize;
  for sb in st.SmallBlockTypeStates do begin
    result := result + sb.UseableBlockSize * sb.AllocatedBlockCount;
  end;
end;

The best thing about this method is that it's strictly tracked: when you allocate memory, it goes up, and when you deallocate memory, it goes down by the same amount right away. I use this before and after running each of my unit tests, so I can tell which test is leaking memory (for example).