CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
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 namespace edm {
8 // keeps the running average of the last N entries
9 // thread safe, fast: does not garantee precise update in case of collision
11  public:
12  static constexpr int N = 16; // better be a power of 2
13  explicit RunningAverage(unsigned int k=4) : m_mean(N*k), m_curr(0) {
14  for (auto & i : m_buffer) i=k;
15  }
16 
17  int mean() const { return m_mean/N;}
18 
19  int upper() const { auto lm = mean(); return lm+=(std::abs(m_buffer[0]-lm)+std::abs(m_buffer[N/2]-lm)); } // about 2 sigma
20 
21  void update(unsigned int q) {
22  int e=m_curr;
23  while(!m_curr.compare_exchange_weak(e,e+1));
24  int k = (N-1)&e;
25  int old = m_buffer[k];
26  if (!m_buffer[k].compare_exchange_strong(old,q)) return;
27  m_mean+= (q-old);
28  }
29 
30 
31 private:
32  std::array<std::atomic<int>,N> m_buffer;
33  std::atomic<int> m_mean;
34  std::atomic<int> m_curr;
35 
36  };
37 }
38 
39 #endif
40 
41 
int i
Definition: DBlmapReader.cc:9
RunningAverage(unsigned int k=4)
#define constexpr
std::array< std::atomic< int >, N > m_buffer
int upper() const
static constexpr int N
Abs< T >::type abs(const T &t)
Definition: Abs.h:22
std::atomic< int > m_mean
std::atomic< int > m_curr
void update(unsigned int q)