如何测量内存使用情况

4

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


1
如果我没记错的话,FastMM的完整版本包含一个演示内存使用跟踪器程序。听起来这正是你需要的。 - David Heffernan
2
我认为这个主题已经有几个相关的问题了。请参考例如https://dev59.com/wFLTa4cB1Zd3GeqPcqwl或https://dev59.com/ZVLTa4cB1Zd3GeqPdMGW。 - jpfollenius
有人可以评论一下在https://dev59.com/wFLTa4cB1Zd3GeqPcqwl问题中的“Inside - Windows”值吗? - Branko
没有人知道你的意思,Branko。 - Warren P
在这个例子中 - GetMem(P, 1024 * 1024) - FastMem 显示内存使用量为 1.048.768 B,而 GetProcessMemoryInfo() 只显示了 4.096? - Branko
我认为使用Windows函数来获取内存使用情况并不是很有用,因为你只能得到缓存值。查询Delphi内存管理器要好得多。 - Brian Frost
1个回答

1

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

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。


尽管我期望32位进程分配超过2GB内存时应该是NativeUInt,但在Delphi 2009上存在NativeInt。 - David Heffernan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接