Line data Source code
1 : // Copyright (c) 2014 The Bitcoin Core developers
2 : // Distributed under the MIT software license, see the accompanying
3 : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 :
5 : #ifndef BITCOIN_TIMEDATA_H
6 : #define BITCOIN_TIMEDATA_H
7 :
8 : #include <algorithm>
9 : #include <assert.h>
10 : #include <stdint.h>
11 : #include <vector>
12 :
13 : class CNetAddr;
14 :
15 : /**
16 : * Median filter over a stream of values.
17 : * Returns the median of the last N numbers
18 : */
19 : template <typename T>
20 258 : class CMedianFilter
21 : {
22 : private:
23 : std::vector<T> vValues;
24 : std::vector<T> vSorted;
25 : unsigned int nSize;
26 :
27 : public:
28 258 : CMedianFilter(unsigned int size, T initial_value) : nSize(size)
29 : {
30 86 : vValues.reserve(size);
31 86 : vValues.push_back(initial_value);
32 86 : vSorted = vValues;
33 86 : }
34 :
35 91 : void input(T value)
36 : {
37 182 : if (vValues.size() == nSize) {
38 4 : vValues.erase(vValues.begin());
39 : }
40 91 : vValues.push_back(value);
41 :
42 182 : vSorted.resize(vValues.size());
43 273 : std::copy(vValues.begin(), vValues.end(), vSorted.begin());
44 182 : std::sort(vSorted.begin(), vSorted.end());
45 91 : }
46 :
47 7 : T median() const
48 : {
49 14 : int size = vSorted.size();
50 7 : assert(size > 0);
51 7 : if (size & 1) // Odd number of elements
52 : {
53 10 : return vSorted[size / 2];
54 : } else // Even number of elements
55 : {
56 6 : return (vSorted[size / 2 - 1] + vSorted[size / 2]) / 2;
57 : }
58 : }
59 :
60 : int size() const
61 : {
62 340 : return vValues.size();
63 : }
64 :
65 : std::vector<T> sorted() const
66 : {
67 0 : return vSorted;
68 : }
69 : };
70 :
71 : /** Functions to keep track of adjusted P2P time */
72 : int64_t GetTimeOffset();
73 : int64_t GetAdjustedTime();
74 : void AddTimeData(const CNetAddr& ip, int64_t nTime);
75 :
76 : #endif // BITCOIN_TIMEDATA_H
|