views:

2195

answers:

6

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?

A: 

You would probably get more detailed and useful process information (memory usage included) via WMI. And of course, you can call WMI queries from Delphi.

Tim Jarvis
Would you care to give some specifics?
Rob Kennedy
+1  A: 

For Win32 API way, you need GetProcessMemoryInfo function. Here is an example from MSDN page but the code is in C++. I think you can convert it to Delphi as well. What you are looking is probably called "Working Set Size."

#include <windows.h>
#include <stdio.h>
#include <psapi.h>

void PrintMemoryInfo( DWORD processID )
{
    HANDLE hProcess;
    PROCESS_MEMORY_COUNTERS pmc;

    // Print the process identifier.

    printf( "\nProcess ID: %u\n", processID );

    // Print information about the memory usage of the process.

    hProcess = OpenProcess(  PROCESS_QUERY_INFORMATION |
                                    PROCESS_VM_READ,
                                    FALSE, processID );
    if (NULL == hProcess)
        return;

    if ( GetProcessMemoryInfo( hProcess, &pmc, sizeof(pmc)) )
    {
        printf( "\tPageFaultCount: 0x%08X\n", pmc.PageFaultCount );
        printf( "\tPeakWorkingSetSize: 0x%08X\n", 
                  pmc.PeakWorkingSetSize );
        printf( "\tWorkingSetSize: 0x%08X\n", pmc.WorkingSetSize );
        printf( "\tQuotaPeakPagedPoolUsage: 0x%08X\n", 
                  pmc.QuotaPeakPagedPoolUsage );
        printf( "\tQuotaPagedPoolUsage: 0x%08X\n", 
                  pmc.QuotaPagedPoolUsage );
        printf( "\tQuotaPeakNonPagedPoolUsage: 0x%08X\n", 
                  pmc.QuotaPeakNonPagedPoolUsage );
        printf( "\tQuotaNonPagedPoolUsage: 0x%08X\n", 
                  pmc.QuotaNonPagedPoolUsage );
        printf( "\tPagefileUsage: 0x%08X\n", pmc.PagefileUsage ); 
        printf( "\tPeakPagefileUsage: 0x%08X\n", 
                  pmc.PeakPagefileUsage );
    }

    CloseHandle( hProcess );
}

int main( )
{
    // Get the list of process identifiers.

    DWORD aProcesses[1024], cbNeeded, cProcesses;
    unsigned int i;

    if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )
        return 1;

    // Calculate how many process identifiers were returned.

    cProcesses = cbNeeded / sizeof(DWORD);

    // Print the memory usage for each process

    for ( i = 0; i < cProcesses; i++ )
        PrintMemoryInfo( aProcesses[i] );

    return 0;
}
m3rLinEz
Thanks for starting it off. Right answer but wrong language and too complicated.
lkessler
+3  A: 

You can look at an example on how to use FastMM with the UsageTrackerDemo project that comes included with the Demos when you download the complete FastMM4 bundle from SourceForge.

François
+3  A: 

I wrote this small function to return the current process (app) memory usage:

function ProcessMemory: longint;
var
  pmc: PPROCESS_MEMORY_COUNTERS;
  cb: Integer;
begin
  // Get the used memory for the current process
  cb := SizeOf(TProcessMemoryCounters);
  GetMem(pmc, cb);
  pmc^.cb := cb;
  if GetProcessMemoryInfo(GetCurrentProcess(), pmc, cb) then
     Result:= Longint(pmc^.WorkingSetSize);

  FreeMem(pmc);
end;
Gerard
Why use GetMem? Just declare a TProcessmemoryCounters variable right there instead of using a dynamic one.
Rob Kennedy
This is the answer, with Rob's optimization.
lkessler
+1  A: 

From an old blog post of mine.

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;

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.

Jim McKeeth
Sorry Jim. Gerard got it first.
lkessler
+7  A: 

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

function MemoryUsed: cardinal;
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).

apenwarr
This method is valid when using FastMM4 or delphi 2006+, but if you are not using FastMM4, you should consider start using it!
Khalid