What is the best way to measure the memory used by a C++ program or a block in a C++ program. The measurement code should thereby be part of the code and it should not be measured from outside. I know of the difficulty of that task, so it does not have to be 100% accurate but at least give me a good impression of the memory usage.
Class level override of the new
and delete
operators are what you want.
Overloading new
and delete
is probably the way to go. Not only on a specific class but maybe more general. But you also need to mark where the new
and delete
is made. And have some kind of start/reset or something to mark now you enter this block, and now you exit the block. And then you need to keep the history to be able to monitor it after it happened.
Measuring at the block level will be difficult (at best) unless you're willing to explicitly add instrumentation directly to the code under test.
I wouldn't start with overloads of new
and delete
at the class level to try to do this. Instead, I'd use overloads of ::operator new
and ::operator delete
. That's basically the tip of the funnel (so to speak) -- all the other dynamic memory management eventually comes down to calling those (and most do so fairly directly). As such, they will generally do the most to tell you about dynamic memory usage of the program as a whole.
The main time you'd need to deal with overloads of new
and delete
for an individual class would be if they're already overloaded so they're managing a separate pool, and you care about how much of that pool is in use at a given time. In that case, you'd (just about) need to add instrumentation directly to them, to get something like a high-water mark on their memory usage during a given interval.
As others have pointed out, you can overload new and delete to measure how much heap was allocated. To do the same for the stack, if you feel adventurous, you'll have to do some ASM. In GCC in x86-64 to get the stack position:
int64_t x = 0;
asm("movq %%rsp, %0;" : "=r" (x) );
This will put in x the address of the stack pointer. Put this in a few places around your code and compare the values before/after entering the block.
Please note that this might need some work to get what you want because of how/when the compiler might allocate memory; it is not as intuitive or trivial as it sounds.