KevTheDev
KevTheDev

Reputation: 31

Is there a way to measure runtime memory usage of a c++ program?

Basically I'm doing some competitive programming stuf, and I want to check (locally) how much memory is used by my program during runtime. I would like to measure this using another program. Is there a way to do that? If so, can I have the code? Quite confused here.

Would be better if there's a platform-independent way.

Upvotes: 3

Views: 1332

Answers (1)

Michael Veksler
Michael Veksler

Reputation: 8475

Unfortunately, there is no platform-independent way. If you want to measure memory usage outside the program, without changing its code, then you need to use OS specific tools.

On Linux: In Linux, how to tell how much memory processes are using?. It basically tells you to parse /proc/{the process id of the running program}/smaps. A variant of this may work on other systems that have a /proc/ filesystem.

On Windows: How to use GetProcessMemoryInfo in C++?. It requires the HANDLE of the process, which you can get with

handle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, 
                     FALSE, process_id);
PROCESS_MEMORY_COUNTERS couters;
GetProcessMemoryInfo( handle, &counters, sizeof(counters));
CloseHandle(handle);

now do something with counters ....
               

Edit:

There seems to be a Linux (and possibly Mac/OS) tool, oi, to do just that. Although I have never used it, its presentation looks quite impressive.

Upvotes: 2

Related Questions