0

I would like to get some information about the memory usage of my C++ program. The way I do this is by accessing /proc/self/stat and printing the virtual and resident set size.

You can find an example here.

Is this a good way to go? How accurate is the information I am accessing*?

Could someone recommend a better way to measure memory usage programmatically?

*Asking, because I get unexpected, sudden jumps of mem usage. My expectation was that the information is perfectly accurate.

OS: I am running inside a docker container, which is based on RHEL.

Additional info: If I limit the memory usage of the container with docker run -m, the printed memory is greater than the limit I set.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
User12547645
  • 6,955
  • 3
  • 38
  • 69
  • This is *very* dependent on operating system, so please [edit] your question to clearly state that (for example by adding it as a tag). – Some programmer dude Apr 16 '20 at 17:35
  • Does this answer your question? [How to get memory usage at runtime using C++?](https://stackoverflow.com/questions/669438/how-to-get-memory-usage-at-runtime-using-c) – P.P Apr 16 '20 at 17:47
  • @usr It kindof does. The solution there is pretty much what I was using. But I got the strange result, when using this method. This is why I was looking for better ways to do it – User12547645 Apr 16 '20 at 20:49

1 Answers1

2

How to programatically get the memory usage of the current program?

There is no standard way to get memory usage of a program in C++.

The concept of "memory usage" itself is somewhat vague and can mean different things. Depending on what you mean, there may or might not be a system specific way to get the information.

The way I do this is by accessing /proc/self/stat

Is this a good way to go?

I don't think so. As far as I know, /proc filesystem is not portable. Use the getrusage function on POSIX systems.

Community
  • 1
  • 1
eerorika
  • 232,697
  • 12
  • 197
  • 326