本例效果圖:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Memo1: TMemo;
Memo2: TMemo;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
//測試堆的內存占用情況
procedure TForm1.Button1Click(Sender: TObject);
var
MyHeap: THandle;
mem: TMemoryStatus;
m1,m2,m3: DWord;
begin
{獲取當前內存可用狀態}
GlobalMemoryStatus(mem);
m1 := mem.dwAvailPhys; {可用物理內存}
m2 := mem.dwAvailPageFile; {可用虛擬內存}
m3 := mem.dwAvailVirtual; {可用虛擬地址}
{建立私有堆}
MyHeap := HeapCreate(HEAP_NO_SERIALIZE, 1024*1204, 0); {建立 1 M 大小的堆}
{再獲取當前內存可用狀態}
GlobalMemoryStatus(mem);
m1 := m1 - mem.dwAvailPhys;
m2 := m2 - mem.dwAvailPageFile;
m3 := m3 - mem.dwAvailVirtual;
{顯示堆占用內存的情況}
Memo1.Clear;
Memo1.Lines.Add(Format('占用物理內存: %d K', [m1 div 1024]));
Memo1.Lines.Add(Format('占用虛擬內存: %d K', [m2 div 1024]));
Memo1.Lines.Add(Format('占用虛擬地址: %d K', [m3 div 1024]));
{釋放堆}
HeapDestroy(MyHeap);
end;
//同上個過程, 外加測試建立堆時頁對齊的情況
procedure TForm1.Button2Click(Sender: TObject);
var
MyHeap: THandle;
mem: TMemoryStatus;
m1,m2,m3: DWord;
begin
GlobalMemoryStatus(mem);
m1 := mem.dwAvailPhys;
m2 := mem.dwAvailPageFile;
m3 := mem.dwAvailVirtual;
{建立 1M + 1字節 大小的堆, 但實際大小會按頁對齊, 結果應該是: 1M + 4K}
MyHeap := HeapCreate(HEAP_NO_SERIALIZE, 1024*1204 + 1, 0);
GlobalMemoryStatus(mem);
m1 := m1 - mem.dwAvailPhys;
m2 := m2 - mem.dwAvailPageFile;
m3 := m3 - mem.dwAvailVirtual;
Memo2.Clear;
Memo2.Lines.Add(Format('占用物理內存: %d K', [m1 div 1024]));
Memo2.Lines.Add(Format('占用虛擬內存: %d K', [m2 div 1024]));
Memo2.Lines.Add(Format('占用虛擬地址: %d K', [m3 div 1024]));
HeapDestroy(MyHeap);
end;