Fix image links in README.md
[junction.git] / junction / Averager.h
1 /*------------------------------------------------------------------------
2   Junction: Concurrent data structures in C++
3   Copyright (c) 2016 Jeff Preshing
4
5   Distributed under the Simplified BSD License.
6   Original location: https://github.com/preshing/junction
7
8   This software is distributed WITHOUT ANY WARRANTY; without even the
9   implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10   See the LICENSE file for more information.
11 ------------------------------------------------------------------------*/
12
13 #ifndef JUNCTION_AVERAGER_H
14 #define JUNCTION_AVERAGER_H
15
16 #include <junction/Core.h>
17 #include <vector>
18 #include <algorithm>
19
20 namespace junction {
21
22 class Averager {
23 private:
24     std::vector<double> m_values;
25     bool m_finalized;
26
27 public:
28     Averager() : m_finalized(false) {
29     }
30
31     void add(double value) {
32         TURF_ASSERT(!m_finalized);
33         m_values.push_back(value);
34     }
35
36     ureg getNumValues() const {
37         return m_values.size();
38     }
39
40     void finalize(ureg bestValueCount = 0) {
41         if (!m_finalized) {
42             std::sort(m_values.begin(), m_values.end());
43             if (bestValueCount)
44                 m_values.resize(bestValueCount);
45             m_finalized = true;
46         }
47     }
48
49     double getAverage() {
50         finalize();
51         double sum = 0;
52         for (ureg i = 0; i < m_values.size(); i++) {
53             sum += m_values[i];
54         }
55         return sum / m_values.size();
56     }
57
58     double getStdDev();
59 };
60
61 } // namespace junction
62
63 #endif // JUNCTION_AVERAGER_H