简体   繁体   中英

C++. How to get maximum amount of memory allocated by a process from it's start?

I want to know the maximum amount of heap allocated by the process during it's work.

mallinfo() gives me amount of currently allocated memory. So, I can ask allinfo() frequently in separate thread and store the maximum value.

But, maybe, such information about a process are written somewhere in the system? First of all I'm interested in Windows.

不,系统中没有地方可以跟踪进程自启动以来所使用的最大堆内存量。

If it's only for profiling, you can use a profiling tool, like valgrind's massif. I don't know what tools there are for windows, but there certainly are.

For MS-Windows,you want to use the GetProcessMemoryInfo() function. This gives you a structure with various sizes. You'll want to test to see what's what for yourselves, but I think it is fairly well documented.

You will get a structure that looks like this:

typedef struct _PROCESS_MEMORY_COUNTERS {
  DWORD  cb;
  DWORD  PageFaultCount;
  SIZE_T PeakWorkingSetSize;
  SIZE_T WorkingSetSize;
  SIZE_T QuotaPeakPagedPoolUsage;
  SIZE_T QuotaPagedPoolUsage;
  SIZE_T QuotaPeakNonPagedPoolUsage;
  SIZE_T QuotaNonPagedPoolUsage;
  SIZE_T PagefileUsage;
  SIZE_T PeakPagefileUsage;
} PROCESS_MEMORY_COUNTERS, *PPROCESS_MEMORY_COUNTERS;

For Linux there is an interface which escaped me at this point, but you can also find the information in the status file of the process. So from the process itself, you do getpid() and read the status file from that:

std::string status_filename("/proc/" + std::to_string(getpid()) + "/status");
std::ifstream status(status_filename, std::ios::in);
... // read file 'status'

The lines that start with Vm are those that interest you. For example, VmPeak will tell you the maximum amount of memory ever used by your process.

More reading about Runtime Memory Measurement under Linux.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM