3

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.

KevTheDev
  • 31
  • 1
  • If there isn't a platform independent way, do you have a platform in mind? – Bill Lynch Jul 12 '20 at 05:16
  • 1
    There's certainly no platform independent way. – john Jul 12 '20 at 05:21
  • 1
    Heaptrack is one way (linux). Another hacky way is to overload `new`, `delete` operators and count of your allocations. – Waqar Jul 12 '20 at 06:11
  • 2
    @Waqar don't forget `malloc` and `free`. I once worked in a project where they overloaded all relevant `new` and `delete` operators, and defined macros for `malloc` and `free`. This mostly worked, except for memory issues due to fragmentation. – Michael Veksler Jul 12 '20 at 06:41

1 Answers1

2

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 ....
               
Michael Veksler
  • 8,217
  • 1
  • 20
  • 33