Get Current Process Memory

Want to know how much memory your program is using? This Delphi function will do the trick.

uses psAPI; 
{...}
function CurrentProcessMemory: Cardinal;
var
  MemCounters: TProcessMemoryCounters;
begin
  MemCounters.cb := SizeOf(MemCounters);
  if GetProcessMemoryInfo(GetCurrentProcess, 
      @MemCounters, 
      SizeOf(MemCounters)) then
    Result := MemCounters.WorkingSetSize
  else
    RaiseLastOSError;
end;

Update: Thanks to Andreas for a heap free (no GetMem / FreeMem) method of doing this (via his comment!)

Not sure where I got the basics of this, but I added some better error handling to it and made it a function. WorkingSetSize is the amount of memory currently used. You can use similar code to get other values for the current process (or any process). You will need to include psAPI in your uses statement.

The PROCESS_MEMORY_COUNTERS record includes:

  • PageFaultCount
  • PeakWorkingSetSize
  • WorkingSetSize
  • QuotaPeakPagedPoolUsage
  • QuotaPagedPoolUsage
  • QuotaPeakNonPagedPoolUsage
  • QuotaNonPagedPoolUsage
  • PagefileUsage
  • PeakPagefileUsage

You can find all of these values in Task Manager or Process Explorer.

Maybe this would be a good task for one of Delphi’s new records that include methods. . . .

It would appear

One Response to “Get Current Process Memory”

  1. Andreas Hausladen says:

    Why do you allocate memory on the heap. The stack would do the same without the need for a try/finally block.

    function CurrentProcessMemory: Cardinal;
    var
    MemCounters: TProcessMemoryCounters;
    begin
    MemCounters.cb := SizeOf(MemCounters);
    if GetProcessMemoryInfo(GetCurrentProcess,
    @MemCounters,
    SizeOf(MemCounters)) then
    Result := MemCounters.WorkingSetSize
    else
    RaiseLastOSError;
    end;