53

我知道如何使用 GlobalMemoryStatusEx 获取系统内存使用情况,但这告诉我整个操作系统正在使用什么。

我真的希望我的程序报告它单独分配和使用了多少内存。

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


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

4

6 回答 6

82

您可以从 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;

这种方法最好的地方是它被严格跟踪:当你分配内存时,它会上升,而当你释放内存时,它会立即下降相同的数量。我在运行每个单元测试之前和之后都使用它,所以我可以判断哪个测试正在泄漏内存(例如)。

于 2009-02-17T19:08:04.003 回答
26

来自我的一篇旧博文

想知道您的程序使用了多少内存?这个 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 是当前使用的内存量。您可以使用类似的代码来获取当前进程(或任何进程)的其他值。您需要在您的使用声明中包含 psAPI。

PROCESS_MEMORY_COUNTERS记录包括:

  • PageFaultCount
  • 峰值工作集大小
  • 工作集大小
  • QuotaPeakPagedPoolUsage
  • QuotaPagedPoolUsage
  • QuotaPeakNonPagedPoolUsage
  • QuotaNonPagedPoolUsage
  • 页面文件使用
  • PeakPagefileUsage

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

于 2009-01-14T08:26:14.867 回答
4

当您从 SourceForge 下载完整的 FastMM4 包时,您可以查看一个示例,了解如何将 FastMM 与演示附带的 UsageTrackerDemo 项目一起使用。

于 2009-01-13T02:08:34.180 回答
4

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

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;
于 2009-01-13T02:56:29.713 回答
2

将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.
于 2018-01-03T23:26:36.183 回答
1

对于 Win32 API 方式,您需要GetProcessMemoryInfo函数。这是来自MSDN 页面的示例,但代码使用 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;
}
于 2009-01-13T01:34:22.313 回答