Add statistics code to destructors of containers in std header files. This does not require to modify big amount of code of big project too. But this show only container type too (see my another answer here). Method does not require C++0x or C++11 or any more.
First and mandatory step is to add your std libary under source control, git for example, for quick view what is actually changed and for quick switch between modified and original version.
Place this declaration of Stat
class into std library sources folder:
class Stat {
std::map<std::string,int> total;
std::map<std::string,int> maximum;
public:
template<class T>
int log( std::string cont, size_t size ) {
std::string key = cont + ": " + typeid(T).name();
if( maximum[key] < size ) maximum[key] = size;
total[key] += size;
}
void show_result() {
std::cout << "container type total maximum" << std::endl;
std::map<std::string,int>::const_iterator it;
for( it = total.begin(); it != total.end(); ++it ) {
std::cout << it->first << " " << it->second
<< " " << maximum[it->first] << std::endl;
}
}
static Stat& instance();
~Stat(){ show_result(); }
};
Instantiate instance of singleton of Stat
class at your project cpp file:
Stat& Stat::instance() {
static Stat stat;
return stat;
}
Edit the std library container templates. Add statistic loggering at destructors.
// modify this standart template library sources:
template< T, Allocator = std::allocator<T> > vector {
...
virtual ~vector() {
Stat::instance().log<value_type>( "std::vector", this->size() );
}
};
template< Key, T, Compare = std::less<Key>,
Allocator = std::allocator<std::pair<const Key, T> > map {
...
virtual ~map(){
Stat::instance().log<value_type>( "std::map", this->size() );
}
};
Consider a program for example now:
int main() {
{
// reject to use C++0x, project does not need such dependency
std_vector<int> v1; for(int i=0;i<10;++i) v1.push_back( i );
std_vector<int> v2; for(int i=0;i<10;++i) v2.push_back( i );
std_map<int,std::string> m1; for(int i=0;i<10;++i) m1[i]="";
std_map<int,std::string> m2; for(int i=0;i<20;++i) m2[i]="";
}
Stat::instance().show_result();
return 0;
}
The result for gcc is:
container type total maximum
std::map: St4pairIiSsE 30 20
std::vector: i 20 10
If you need more detailed type desription than find information concerning your development environment. Such conversion described here for gcc: https://lists.gnu.org/archive/html/help-gplusplus/2009-02/msg00006.html
Output may be like this:
container type total maximum
std::map: std::pair<int, std::string> 30 20
std::vector: int 20 10