Statistics.h 2.08 KB
Newer Older
adelmann's avatar
adelmann committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
#ifndef __STATISTICS_H__
#define __STATISTICS_H__

#include <map>
#include <string>
#include <iostream>

template<typename T>
class Statistics {

public:

    Statistics(std::string name) : stat_name_(name) {}
    ~Statistics() {}

    void registerStatistic(std::string name, T initial_value = 0) {
        std::pair<statistics_iterator_t, bool> statistic_position;
        statistic_position = statistics_.insert(std::pair<std::string, T>(name, initial_value));

        if(statistic_position.second == false)
            std::cout << "Statistic " << statistic_position.first->second << " already exists!" << std::endl;
    }

    void changeStatisticBy(std::string name, T change_by_value) {
        statistics_iterator_t name_at;
        name_at = statistics_.find(name);

        if(name_at != statistics_.end())
            statistics_[name] += change_by_value;
        else
            std::cout << "Statistic " << name << " not registered!" << std::endl;
    }

    T getStatisticValue(std::string name) {
        return statistics_[name];
    }

    void dumpStatistics() {
        std::cout << "Statistics: " << stat_name_ << std::endl;

        T sum = 0;
42
        for(std::pair<std::string, T> stat : statistics_) {
adelmann's avatar
adelmann committed
43 44 45 46 47 48 49 50 51 52 53 54
            sum += stat.second;
            std::cout << "\t" << stat.first << " = " << stat.second << std::endl;
        }

        std::cout << "_________________________" << std::endl;
        std::cout << "Total: " << sum << std::endl;
    }

    void dumpStatistics(std::ostringstream &stream) {
        stream << "Statistics: " << stat_name_ << std::endl;

        T sum = 0;
55
        for (std::pair<std::string, T> stat : statistics_) {
adelmann's avatar
adelmann committed
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
            sum += stat.second;
            stream << "\t" << stat.first << " = " << stat.second << std::endl;
        }

        stream << "_________________________" << std::endl;
        stream << "Total: " << sum << std::endl;
    }


private:

    typedef typename std::map<std::string, T> statistics_t;
    typedef typename std::map<std::string, T>::iterator statistics_iterator_t;

    statistics_t statistics_;
    std::string stat_name_;

};

#endif