stream  0.10.0
stream analysis framework
Profiler.h
1 // Copy of source from DABC Profiler
2 
3 #ifndef BASE_PROFILER_H
4 #define BASE_PROFILER_H
5 
6 #include <string>
7 #include <vector>
8 
9 namespace base {
10 
11  class ProfilerGuard;
12 
15  class Profiler {
16 
17  friend class ProfilerGuard;
18 
19  typedef unsigned long long clock_t;
20 
21  bool fActive{true};
22 
23  clock_t GetClock()
24  {
25 
26 #ifdef STREAM_AARCH64
27  uint64_t virtual_timer_value;
28  asm volatile("mrs %0, cntvct_el0" : "=r"(virtual_timer_value));
29  return virtual_timer_value;
30 #else
31  unsigned low, high;
32  asm volatile ("rdtsc" : "=a" (low), "=d" (high));
33  return (clock_t(high) << 32) | low;
34 #endif
35  }
36 
37  clock_t fLast{0};
38 
40  struct Entry {
41  clock_t fSum{0};
42  double fRatio{0.};
43  std::string fName;
44  };
45 
46  std::vector<Entry> fEntries;
47 
48  public:
49 
51  Profiler() { Reserve(10); }
52 
54  void Reserve(unsigned num = 10)
55  {
56  while (fEntries.size() < num)
57  fEntries.emplace_back();
58  }
59 
61  void SetActive(bool on = true) { fActive = on; }
62 
63  void MakeStatistic();
64 
65  std::string Format();
66 
67  };
68 
71  class ProfilerGuard {
72  Profiler &fProfiler;
73  unsigned fCnt{0};
74  Profiler::clock_t fLast{0};
75 
76  public:
78  ProfilerGuard(Profiler &prof, const char *name = nullptr, unsigned lvl = 0) : fProfiler(prof), fCnt(lvl)
79  {
80  if (!fProfiler.fActive || (fCnt >= fProfiler.fEntries.size()))
81  return;
82 
83  fLast = fProfiler.GetClock();
84 
85  if (name && fProfiler.fEntries[fCnt].fName.empty())
86  fProfiler.fEntries[fCnt].fName = name;
87  }
88 
91  {
92  Next();
93  }
94 
96  void Next(const char *name = nullptr, unsigned lvl = 0)
97  {
98  if (!fProfiler.fActive || (fCnt >= fProfiler.fEntries.size()))
99  return;
100 
101  auto now = fProfiler.GetClock();
102 
103  fProfiler.fEntries[fCnt].fSum += (now - fLast);
104 
105  fLast = now;
106 
107  if (lvl) fCnt = lvl; else fCnt++;
108 
109  if (name && (fCnt < fProfiler.fEntries.size()) && fProfiler.fEntries[fCnt].fName.empty())
110  fProfiler.fEntries[fCnt].fName = name;
111  }
112 
113  };
114 
115 } // namespace dabc
116 
117 #endif
Guard class to use base::Profiler.
Definition: Profiler.h:71
~ProfilerGuard()
destructor
Definition: Profiler.h:90
ProfilerGuard(Profiler &prof, const char *name=nullptr, unsigned lvl=0)
constructor
Definition: Profiler.h:78
void Next(const char *name=nullptr, unsigned lvl=0)
next ?
Definition: Profiler.h:96
Performance profiler.
Definition: Profiler.h:15
void MakeStatistic()
make statistic
Definition: Profiler.cxx:6
std::string Format()
format
Definition: Profiler.cxx:26
void SetActive(bool on=true)
set active
Definition: Profiler.h:61
Profiler()
constructor
Definition: Profiler.h:51
void Reserve(unsigned num=10)
reserve
Definition: Profiler.h:54