Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining process virtual size using delphi

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.

like image 979
Name Avatar asked Nov 16 '11 13:11

Name


2 Answers

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.

like image 140
Name Avatar answered Nov 16 '22 14:11

Name


Process Explorer seems to do it by calling NtQueryInformation but it's also possible to use performance data, see GetProcessVirtualBytes in my answer here.

like image 6
Ondrej Kelle Avatar answered Nov 16 '22 15:11

Ondrej Kelle