test
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 // Function for testing RunningAverage
8 namespace test {
9  namespace running_average {
10  int test();
11  }
12 }
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) i=k;
25  }
26 
27  int mean() const { return m_mean/N;}
28 
29  int upper() const { auto lm = mean(); return lm+=(std::abs(m_buffer[0]-lm)+std::abs(m_buffer[N/2]-lm)); } // about 2 sigma
30 
31  void update(unsigned int q) {
32  int e=m_curr;
33  while(!m_curr.compare_exchange_weak(e,e+1));
34  int k = (N-1)&e;
35  int old = m_buffer[k];
36  if (!m_buffer[k].compare_exchange_strong(old,q)) return;
37  m_mean+= (q-old);
38  }
39 
40 
41 private:
42  std::array<std::atomic<int>,N> m_buffer;
43  std::atomic<int> m_mean;
44  std::atomic<int> m_curr;
45 
46  };
47 }
48 
49 #endif
50 
51 
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)