Memory Allocation Profiling in C++
I am writing an application and am surprised to see its total memory usage is already too high. I want to profile the dynamic memory usage of my application: How many objects of each kind are there in the heap, and which functions created these objects? Also, how much memory is used by each of the object?
Is there a simple way to do this? I am working on both linux and windows, so tools of any of the platforms would suffice.
NOTE: I am not concerned with memory leaks here.
Have you tried Valgrind? It is a profiling tool for Linux. It has a memory checker (for memory leaks and other memory problems) called Memcheck but it has also a heap profiler named Massif.
For simple statistics, just to find out where all the memory is used, you could add a template like this:
template<class T>
class Stats {
static int instance_count;
public:
Stats() {
instance_count++;
}
~Stats() {
instance_count--;
}
static void print() {
std::cout << instance_count << " instances of " << typeid(T).name() <<
", " << sizeof(T) << " bytes each." << std::endl;
}
};
template<class T>
int Stats<T>::instance_count = 0;
Then you can add this as a base class to the classes you suspect to have a lot of instances, and print out statistics of the current memory usage:
class A : Stats<A> {
};
void print_stats() {
Stats<A>::print();
Stats<B>::print();
...
}
This doesn't show you in which functions the objects were allocated and doesn't give too many details, but it might me enough to locate where memory is wasted.
For windows check the functions in "crtdbg.h". crtdbg.h contains the debug version of memory allocation functions. It also contains function for detecting memory leaks, corruptions, checking the validity of heap pointers, etc.
I think following functions will be useful for you.
_CrtMemDumpStatistics _CrtMemDumpAllObjectsSince
Following MSDN link lists the Heap State Reporting functions and sample code http://msdn.microsoft.com/en-us/library/wc28wkas(VS.80).aspx