What is the most accurate way to find out the current physical memory usage by my program ?

What is the most accurate way to find out the current physical memory (RAM) being used by my c++ program in linux using c++.

I am looking for something like :

1
2
3
4
5
6
7
8
9
void func() {
  std::cout << "Memory before : " << GetCurrentMemoryUsageByThisProcess();
  int arr1[100];
  // allocate more memory
  int* arr2 = new int[200];
  std::cout << GetCurrentMemoryUsageByThisProcess();
  std::cout << "Memory after : " << GetCurrentMemoryUsageByThisProcess();
  return;
}


Example Output :

Memory before : 1024 //this is a random value just as example.
Memory after : 2048  //this is a random value just as example.
Last edited on
Need to call into your system's API.

Here's a StackOverflow answer I found, might help: https://stackoverflow.com/a/14927379/8690169

Note that it isn't going to be 1024 or what have you, there's a lot more going on.
e.g. I just tried this and got 7016448 as the answer.
Last edited on
Thanks Ganado for having a look.

I have a follow up question. In the link you have mentioned, while getting memory info from /proc/self/statm;
how frequently is this updated ?
Does this provide real time memory usage ?
That I don't know. I don't know how often statm is updated.
But this link: https://unix.stackexchange.com/questions/329758/how-quickly-often-are-process-memory-measurements-updated-in-the-kernel
claims that someone said "/proc/.../statm is current as soon as you read it since reading it directly triggers kernel callbacks."

Here is the post he's referring to: https://unix.stackexchange.com/questions/74713/how-frequently-is-the-proc-file-system-updated-on-linux

http://man7.org/linux/man-pages/man5/proc.5.html just says
The proc filesystem is a pseudo-filesystem which provides an
interface to kernel data structures.


May another user will have more insight.
Last edited on
why do you need this? The os can tell you without writing code (eg, task manager or top or the like) if you just want the number. If you need it from code, its going to be a call to an OS library, as noted.
Thanks Ganado for all the useful info !
Topic archived. No new replies allowed.