gpt4 book ai didi

delphi - 为什么释放内存后我的程序的内存使用量没有恢复正常?

转载 作者:行者123 更新时间:2023-12-03 14:51:01 25 4
gpt4 key购买 nike

考虑下一个示例应用程序

program TestMemory;


{$APPTYPE CONSOLE}

uses
PsAPI,
Windows,
SysUtils;

function GetUsedMemoryFastMem: cardinal;
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;

function GetUsedMemoryWindows: longint;
var
ProcessMemoryCounters: TProcessMemoryCounters;
begin
Result:=0;
ProcessMemoryCounters.cb := SizeOf(TProcessMemoryCounters);
if GetProcessMemoryInfo(GetCurrentProcess(), @ProcessMemoryCounters, ProcessMemoryCounters.cb) then
Result:= ProcessMemoryCounters.WorkingSetSize
else
RaiseLastOSError;
end;

procedure Test;
const
Size = 1024*1024;
var
P : Pointer;
begin
GetMem(P,Size);

Writeln('Inside');
Writeln('FastMem '+FormatFloat('#,', GetUsedMemoryFastMem));
Writeln('Windows '+FormatFloat('#,', GetUsedMemoryWindows));
Writeln('');

FreeMem(P);
end;

begin
Writeln('Before');
Writeln('FastMem '+FormatFloat('#,', GetUsedMemoryFastMem));
Writeln('Windows '+FormatFloat('#,', GetUsedMemoryWindows));
Writeln('');

Test;

Writeln('After');
Writeln('FastMem '+FormatFloat('#,', GetUsedMemoryFastMem));
Writeln('Windows '+FormatFloat('#,', GetUsedMemoryWindows));
Writeln('');
Readln;
end.

应用程序返回的结果是

Before
FastMem 1.844
Windows 3.633.152

Inside
FastMem 1.050.612
Windows 3.637.248

After
FastMem 2.036
Windows 3.633.152

我想知道为什么BeforeAfter的内存使用结果不同:

最佳答案

任何内存管理器(包括 FastMM)都会产生一些开销,否则 Delphi 可能只使用 Windows 内存管理。

您观察到的差异是开销:

  • FastMM 用于跟踪内存使用情况的结构,
  • FastMM 尚未返回到 Windows 内存管理以优化 future 类似内存分配的内存。

关于delphi - 为什么释放内存后我的程序的内存使用量没有恢复正常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4448129/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com