如何获取 Delphi 程序使用的内存 [英] How to get the Memory Used by a Delphi Program

查看:50
本文介绍了如何获取 Delphi 程序使用的内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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?

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

Revisiting my question, I have now changed my accepted answer to the GetMemoryManagerState answer by @apenwarr. It produced identical results to the GetHeapStatus function (now deprecated) that I used to use, whereas GetProcessMemoryInfo.WorkingSetSize gave a very different result.

推荐答案

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

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

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;

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

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).

这篇关于如何获取 Delphi 程序使用的内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆