DIY  3.0
data-parallel out-of-core C++ library
 All Classes Namespaces Functions Typedefs Groups Pages
stats.hpp
1 #ifndef DIY_STATS_HPP
2 #define DIY_STATS_HPP
3 
4 #include <chrono>
5 #include <string>
6 #include <vector>
7 
8 #include "log.hpp" // need this for format
9 
10 namespace diy
11 {
12 namespace stats
13 {
14 
15 #if defined(DIY_PROFILE)
16 struct Profiler
17 {
18  using Clock = std::chrono::high_resolution_clock;
19  using Time = Clock::time_point;
20 
21  struct Event
22  {
23  Event(const std::string& name_, bool begin_):
24  name(name_),
25  begin(begin_),
26  stamp(Clock::now())
27  {}
28 
29  std::string name;
30  bool begin;
31  Time stamp;
32  };
33 
34  using EventsVector = std::vector<Event>;
35 
36  struct Scoped
37  {
38  Scoped(Profiler& prof_, std::string name_):
39  prof(prof_), name(name_), active(true) { prof << name; }
40  ~Scoped() { if (active) prof >> name; }
41 
42  Scoped(Scoped&& other):
43  prof(other.prof),
44  name(other.name),
45  active(other.active) { other.active = false; }
46 
47  Scoped&
48  operator=(Scoped&& other) = delete;
49  Scoped(const Scoped&) = delete;
50  Scoped&
51  operator=(const Scoped&) = delete;
52 
53  Profiler& prof;
54  std::string name;
55  bool active;
56  };
57 
58  Profiler() { reset_time(); }
59 
60  void reset_time() { start = Clock::now(); }
61 
62  void operator<<(std::string name) { enter(name); }
63  void operator>>(std::string name) { exit(name); }
64 
65  void enter(std::string name) { events.push_back(Event(name, true)); }
66  void exit(std::string name) { events.push_back(Event(name, false)); }
67 
68  void output(std::ostream& out)
69  {
70  for (size_t i = 0; i < events.size(); ++i)
71  {
72  const Event& e = events[i];
73  auto time = std::chrono::duration_cast<std::chrono::microseconds>(e.stamp - start).count();
74 
75  fmt::print(out, "{:02d}:{:02d}:{:02d}.{:06d} {}{}\n",
76  time/1000000/60/60,
77  time/1000000/60 % 60,
78  time/1000000 % 60,
79  time % 1000000,
80  (e.begin ? '<' : '>'),
81  e.name);
82  }
83  }
84 
85  Scoped scoped(std::string name) { return Scoped(*this, name); }
86 
87  void clear() { events.clear(); }
88 
89  private:
90  Time start;
91  EventsVector events;
92 };
93 #else
94 struct Profiler
95 {
96  struct Scoped {};
97 
98  void reset_time() {}
99 
100  void operator<<(std::string) {}
101  void operator>>(std::string) {}
102 
103  void enter(const std::string&) {}
104  void exit(const std::string&) {}
105 
106  void output(std::ostream&) {}
107  void clear() {}
108 
109  Scoped scoped(std::string) { return Scoped(); }
110 };
111 #endif
112 }
113 }
114 
115 #endif
Definition: stats.hpp:94
Definition: stats.hpp:96