如何获得Delphi程序使用的内存

问题描述 投票:46回答:6

我知道如何使用GlobalMemoryStatusEx来使用系统内存,但这可以告诉我整个操作系统在使用什么。

我真的希望我的程序报告它单独分配并正在使用的内存量。

我的Delphi 2009程序中是否有任何方法可以调用Windows函数或某些FastMM函数来查找仅由我的程序分配的内存?


重新回答我的问题,我现在已将@apenwarr更改为GetMemoryManagerState答案的已接受答案。它产生的结果与我以前使用的GetHeapStatus函数(现已不建议使用)相同,而GetProcessMemoryInfo.WorkingSetSize给出了非常不同的结果。

delphi memory-management fastmm
6个回答
70
投票

您可以从Delphi运行时中获得有用的内存使用信息,而无需使用任何直接的Win32调用:

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;

关于此方法的最好之处在于,它受到严格跟踪:分配内存时,它会上升,而释放内存时,它会立即下降相同的数量。我在运行每个单元测试之前和之后都使用它,所以我可以知道哪个测试正在泄漏内存(例如)。


22
投票

From an old blog post of mine

想知道您的程序正在使用多少内存?这个Delphi函数可以解决问题。

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;

不确定我从哪里获得了基础知识,但是我向它添加了一些更好的错误处理并使之具有功能。 WorkingSetSize是当前使用的内存量。您可以使用类似的代码来获取当前进程(或任何进程)的其他值。您将需要在uses语句中包括psAPI。

PROCESS_MEMORY_COUNTERS记录包括:

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

您可以在任务管理器或进程资源管理器中找到所有这些值。


4
投票

[当您从SourceForge下载完整的FastMM4捆绑包时,您可以查看有关如何将FastMM与Demo附带的UsageTrackerDemo项目一起使用的示例。


4
投票

我编写了这个小函数来返回当前进程(应用程序)的内存使用情况:

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;

1
投票

对于Win32 API,您需要GetProcessMemoryInfo函数。这是MSDN page中的示例,但是代码是C ++。我认为您也可以将其转换为Delphi。您正在查找的内容可能称为“工作集大小”。

#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;
}

1
投票

Gant C ++代码转换为Delphi中的控制台应用程序:

    program MemoryProcessCMD;

    {* Based in Gant(https://stackoverflow.com/users/12460/gant) code*}


    {$APPTYPE CONSOLE}
    {$R *.res}

    uses
      System.SysUtils,
      psapi,
      Windows;

    procedure PrintMemoryInfo(processID: DWORD);
    var
      hProcess: THandle;
      pmc: PROCESS_MEMORY_COUNTERS;
      total: DWORD;

    begin

      // Print the process identifier.
      Writeln(format('Process ID: %d', [processID]));

      // Print information about the memory usage of the process.
      hProcess := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, FALSE,
        processID);

      if (hProcess = 0) then
      begin
        exit;
      end;

      if (GetProcessMemoryInfo(hProcess, @pmc, SizeOf(pmc))) then
      begin
        Writeln(format(#09'PageFaultCount: 0x%.8X', [pmc.PageFaultCount]));
        Writeln(format(#09'PeakWorkingSetSize: 0x%.8X', [pmc.PeakWorkingSetSize]));
        Writeln(format(#09'WorkingSetSize: 0x%.8X', [pmc.WorkingSetSize]));
        Writeln(format(#09'QuotaPeakPagedPoolUsage: 0x%.8X',
          [pmc.QuotaPeakPagedPoolUsage]));
        Writeln(format(#09'QuotaPagedPoolUsage: 0x%.8X',
          [pmc.QuotaPagedPoolUsage]));
        Writeln(format(#09'QuotaPeakNonPagedPoolUsage: 0x%.8X',
          [pmc.QuotaPeakNonPagedPoolUsage]));
        Writeln(format(#09'QuotaNonPagedPoolUsage: 0x%.8X',
          [pmc.QuotaNonPagedPoolUsage]));
        Writeln(format(#09'PagefileUsage: 0x%.8X', [pmc.PagefileUsage]));
        Writeln(format(#09'PeakPagefileUsage: 0x%.8X', [pmc.PeakPagefileUsage]));
        Writeln(format(#09'PagefileUsage: 0x%.8X', [pmc.PagefileUsage]));
      end;

      CloseHandle(hProcess);
    end;

    var
      aProcesses: array [0 .. 1024] of DWORD;
      cbNeeded, cProcesses: DWORD;
      i: Integer;

    begin
      try
        // Get the list of process identifiers.
        if (not EnumProcesses(@aProcesses, SizeOf(aProcesses), &cbNeeded)) then
          halt(1);

        // Calculate how many process identifiers were returned.
        cProcesses := cbNeeded div SizeOf(DWORD);

        // Print the memory usage for each process
        for i := 0 to cProcesses - 1 do
        begin
          PrintMemoryInfo(aProcesses[i]);
        end;
      except
        on E: Exception do
          Writeln(E.ClassName, ': ', E.Message);
      end;

    end.
© www.soinside.com 2019 - 2024. All rights reserved.