CMS 3D CMS Logo

RunningAverage.h
Go to the documentation of this file.
1 #ifndef FWCore_Utilities_RunningAverage_H
2 #define FWCore_Utilities_RunningAverage_H
3 #include <atomic>
4 #include <algorithm>
5 #include <array>
6 
7 // Function for testing RunningAverage
8 namespace test_average {
9  namespace running_average {
10  int test();
11  }
12 } // namespace test_average
13 
14 namespace edm {
15  // keeps the running average of the last N entries
16  // thread safe, fast: does not garantee precise update in case of collision
18  // For tests
20 
21  public:
22  static constexpr int N = 16; // better be a power of 2
23  explicit RunningAverage(unsigned int k = 4) : m_mean(N * k), m_curr(0) {
24  for (auto& i : m_buffer)
25  i = k;
26  }
27 
28  int mean() const { return m_mean / N; }
29 
30  int upper() const {
31  auto lm = mean();
32  return lm + (std::abs(m_buffer[0] - lm) + std::abs(m_buffer[N / 2] - lm));
33  } // about 2 sigma
34 
35  void update(unsigned int q) {
36  int e = m_curr;
37  while (!m_curr.compare_exchange_weak(e, e + 1))
38  ;
39  int k = (N - 1) & e;
40  int old = m_buffer[k];
41  if (!m_buffer[k].compare_exchange_strong(old, q))
42  return;
43  m_mean += (q - old);
44  }
45 
46  private:
47  std::array<std::atomic<int>, N> m_buffer;
48  std::atomic<int> m_mean;
49  std::atomic<int> m_curr;
50  };
51 } // namespace edm
52 
53 #endif
RunningAverage(unsigned int k=4)
static constexpr int N
Abs< T >::type abs(const T &t)
Definition: Abs.h:22
std::array< std::atomic< int >, N > m_buffer
std::atomic< int > m_mean
HLT enums.
std::atomic< int > m_curr
void update(unsigned int q)