I have a Delphi program and I'm looking how this program could print its own "virtual size" in a log file, so that I can see when it used too much memory. How can I determine the "virtual size" using Delphi code?
By "virtual size" I mean the value as displayed by Process Explorer. This value can't be displayed by the normal task manager. It is not directly the memory usage of the program but the address space usage. On Win32 a program can not use more than 2 GB of address space.
PS: I'm using Delphi 6 but code/information for other versions should be ok too.
Thanks to this post which gives hints about how to get a virtual size using C/C++, I was able to write the following Delphi function:
Type
TMemoryStatusEx = packed record
dwLength: DWORD;
dwMemoryLoad: DWORD;
ullTotalPhys: Int64;
ullAvailPhys: Int64;
ullTotalPageFile: Int64;
ullAvailPageFile: Int64;
ullTotalVirtual: Int64;
ullAvailVirtual: Int64;
ullAvailExtendedVirtual: Int64;
end;
TGlobalMemoryStatusEx = function(var MSE: TMemoryStatusEx): LongBool; stdcall;
function VirtualSizeUsage: Int64;
var MSE: TMemoryStatusEx;
fnGlobalMemoryStatusEx: TGlobalMemoryStatusEx;
begin
Result := 0;
@fnGlobalMemoryStatusEx := GetProcAddress(GetModuleHandle(kernel32), 'GlobalMemoryStatusEx');
if Assigned(@fnGlobalMemoryStatusEx) then
begin
MSE.dwLength := SizeOf(MSE);
if fnGlobalMemoryStatusEx(MSE) then
Result := MSE.ullTotalVirtual-MSE.ullAvailVirtual;
end;
end;
It seems to works great for me (Delphi 6, Win XP). There might be an easier solution using GlobalMemoryStatus instead of GlobalMemoryStatusEx but it wouldn't work correctly on systems with more than 2 GB memory.
Process Explorer seems to do it by calling NtQueryInformation but it's also possible to use performance data, see GetProcessVirtualBytes
in my answer here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With