statistics.hpp 2.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
#ifndef STATISTICS_HPP
#define STATISTICS_HPP

#include <chrono>
#include <iostream>
#include <string>
#include <unordered_map>

class Statistics {
10
public:
11
  // Increment the counter for a given key by a specified value (default is 1)
12
13
14
  void increment_counter(const std::string &key, int64_t value = 1) {
    counters_[key] += value;
  }
15

16
  int64_t &get_counter(const std::string &key) { return counters_[key]; }
17
18

  // Start the timer for a given key
19
20
21
  void start_timer(const std::string &key) {
    active_timers_[key] = std::chrono::high_resolution_clock::now();
  }
22
23

  // Stop the timer for a given key and update the total time and count
24
  void stop_timer(const std::string &key) {
25
26
    auto start_it = active_timers_.find(key);
    if (start_it != active_timers_.end()) {
27
28
      auto duration =
          std::chrono::high_resolution_clock::now() - start_it->second;
29
30
31
32
33
      timings_[key].total_time += duration;
      timings_[key].count += 1;
      active_timers_.erase(start_it);
    } else {
      // Handle error: stop_timer called without a matching start_timer
34
35
      std::cerr << "Warning: stop_timer called for key '" << key
                << "' without a matching start_timer.\n";
36
37
38
39
40
41
    }
  }

  // Print out the collected statistical information
  void report() const {
    std::cout << "Counters:\n";
42
    for (const auto &kv : counters_) {
43
44
45
      std::cout << "  " << kv.first << ": " << kv.second << "\n";
    }
    std::cout << "\nTimers:\n";
46
    for (const auto &kv : timings_) {
47
48
      std::cout << "  " << kv.first << ": count = " << kv.second.count
                << ", total_time = " << kv.second.total_time.count() << "s"
49
50
51
52
                << ", average_time = "
                << (kv.second.count > 0
                        ? kv.second.total_time.count() / kv.second.count
                        : 0)
53
54
55
56
                << "s\n";
    }
  }

57
private:
58
59
60
61
62
63
  // Mapping from key to counter
  std::unordered_map<std::string, int64_t> counters_;

  // Struct to hold timing information for a key
  struct TimingInfo {
    int64_t count = 0;
64
65
    std::chrono::duration<double> total_time =
        std::chrono::duration<double>::zero();
66
67
68
69
70
71
  };

  // Mapping from key to timing information
  std::unordered_map<std::string, TimingInfo> timings_;

  // Mapping from key to the start time of active timers
72
73
74
  std::unordered_map<std::string,
                     std::chrono::high_resolution_clock::time_point>
      active_timers_;
75
76
};

77
#endif // STATISTICS_HPP