【问题标题】:How to measure the memory usage如何测量内存使用情况
【发布时间】:2012-03-09 08:18:02
【问题描述】:

我正在使用 Delphi 2009 进行编码,我想知道程序使用了多少内存。由于在释放对象时内存管理器不会将未使用的内存释放回操作系统,因此它可能会缓存在内存管理器中以供下次使用。我的问题是是否有可能知道程序使用了多少内存。它应该排除缓存在内存管理器中的内存。谢谢。

【问题讨论】:

  • 如果我没记错的话,完整版的 FastMM 包含一个演示内存使用跟踪程序。这听起来像你需要的。
  • 我想关于这个话题已经有几个问题了。例如,请参阅 *.com/questions/4448129/…*.com/questions/4475592/…
  • 有人可以评论*.com/questions/4448129/…问题中的“Inside - Windows”值
  • 没人知道你的意思,布兰科。
  • 好的。在这个例子中 - GetMem(P, 1024 * 1024) - FastMem show memory usage 1.048.768 B, GetProcessMemoryInfo() only 4.096 ?

标签: delphi


【解决方案1】:

我有一个在调试模式下调用 FastMM 函数来获取内存使用的例程(正如 David 建议的那样)。当未安装 FastMM 时,即在我的发布模式下,我使用以下代码,它只需要引用 Delphi 的系统单元:

function GetAllocatedMemoryBytes_NativeMemoryManager : NativeUInt;
// Get the size of all allocations from the memory manager
var
  MemoryManagerState: TMemoryManagerState;
  SmallBlockState: TSmallBlockTypeState;
  i: Integer;
begin
  GetMemoryManagerState( MemoryManagerState );
  Result := 0;
  for i := low(MemoryManagerState.SmallBlockTypeStates) to
        high(MemoryManagerState.SmallBlockTypeStates) do
    begin
    SmallBlockState := MemoryManagerState.SmallBlockTypeStates[i];
    Inc(Result,
    SmallBlockState.AllocatedBlockCount*SmallBlockState.UseableBlockSize);
    end;

  Inc(Result, MemoryManagerState.TotalAllocatedMediumBlockSize);
  Inc(Result, MemoryManagerState.TotalAllocatedLargeBlockSize);
end;

我使用 XE2,因此您可能需要将 NativeUInt 更改为 Int64。

【讨论】:

  • NativeInt 存在于 delphi 2009 中,尽管我希望它是用于分配超过 2GB 内存的 32 位进程的 NativeUInt。