You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

timedata.h 1.8KB

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