Feb 11, 2020 at 5:10pm UTC
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 Feb 11, 2020 at 5:40pm UTC
Feb 11, 2020 at 5:19pm UTC
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 Feb 11, 2020 at 5:24pm UTC
Feb 11, 2020 at 5:43pm UTC
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 ?
Feb 11, 2020 at 5:51pm UTC
Last edited on Feb 11, 2020 at 5:57pm UTC
Feb 11, 2020 at 6:13pm UTC
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.
Feb 11, 2020 at 7:16pm UTC
Thanks Ganado for all the useful info !