Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

memory

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.

like image 548
KevTheDev Avatar asked Dec 18 '25 11:12

KevTheDev


1 Answers

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.

like image 76
Michael Veksler Avatar answered Dec 20 '25 00:12

Michael Veksler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!