c++linuxmacosgetrusage

Measure the maximum memory usage during a function call


I have a Linux/Mac C++ library that performs a series of steps, in the form of function calls. I would like to measure the maximum memory usage during each step.

I am not interested in ad-hoc solutions like starting another thread that polls memory usage, running a profiler, etc.

So far I have found getrusage() is present on Mac and Linux and does return the maximum memory usage, however there appears to be no way to reset this maximum after each function call.

Is there any way around this limitation?

Edit: To be clear, I do not want to commandeer malloc()/free() and log everything. I want a solution that is suitable to keep in running production code.


Solution

  • I had a browse through the Linux source code, and found this:

            /*
             * Writing 5 to /proc/pid/clear_refs resets the peak
             * resident set size to this mm's current rss value.
             */
    

    I haven't tried it yet but it looks promising.

    Edit: It was added in this commit

    Edit 2: I have looked through the MacOS kernel source - the corresponding value is stored in resident_max. Unfortunately there doesn't seem to be a feature to reset it.

    Edit 3: On Linux you can obtain the maximum allocated memory using malloc_info() however there does not appear to be a way to reset it. It also relies on you using glibc.