Merge pull request #6508
[bitcoinplatinum.git] / src / timedata.h
blob2296baf11bb92acaf5282135464f8a73edb77bc7
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.
5 #ifndef BITCOIN_TIMEDATA_H
6 #define BITCOIN_TIMEDATA_H
8 #include <algorithm>
9 #include <assert.h>
10 #include <stdint.h>
11 #include <vector>
13 class CNetAddr;
15 /**
16 * Median filter over a stream of values.
17 * Returns the median of the last N numbers
19 template <typename T>
20 class CMedianFilter
22 private:
23 std::vector<T> vValues;
24 std::vector<T> vSorted;
25 unsigned int nSize;
27 public:
28 CMedianFilter(unsigned int size, T initial_value) : nSize(size)
30 vValues.reserve(size);
31 vValues.push_back(initial_value);
32 vSorted = vValues;
35 void input(T value)
37 if (vValues.size() == nSize) {
38 vValues.erase(vValues.begin());
40 vValues.push_back(value);
42 vSorted.resize(vValues.size());
43 std::copy(vValues.begin(), vValues.end(), vSorted.begin());
44 std::sort(vSorted.begin(), vSorted.end());
47 T median() const
49 int size = vSorted.size();
50 assert(size > 0);
51 if (size & 1) // Odd number of elements
53 return vSorted[size / 2];
54 } else // Even number of elements
56 return (vSorted[size / 2 - 1] + vSorted[size / 2]) / 2;
60 int size() const
62 return vValues.size();
65 std::vector<T> sorted() const
67 return vSorted;
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);
76 #endif // BITCOIN_TIMEDATA_H