Meter.hpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. * Copyright (c)2019 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2023-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #ifndef ZT_METER_HPP
  14. #define ZT_METER_HPP
  15. #include "Constants.hpp"
  16. #include "Mutex.hpp"
  17. #include "AtomicCounter.hpp"
  18. #define ZT_METER_HISTORY_LENGTH 4
  19. #define ZT_METER_HISTORY_TICK_DURATION 1000
  20. namespace ZeroTier {
  21. /**
  22. * Transfer rate meter (thread-safe)
  23. */
  24. class Meter
  25. {
  26. public:
  27. ZT_ALWAYS_INLINE Meter()
  28. {
  29. for(int i=0;i<ZT_METER_HISTORY_LENGTH;++i)
  30. _history[i] = 0.0;
  31. _ts = 0;
  32. _count = 0;
  33. }
  34. template<typename I>
  35. ZT_ALWAYS_INLINE void log(const int64_t now,I count)
  36. {
  37. const int64_t since = now - _ts;
  38. if (since >= ZT_METER_HISTORY_TICK_DURATION) {
  39. _ts = now;
  40. _history[(unsigned int)(++_hptr) % ZT_METER_HISTORY_LENGTH] = (double)_count / ((double)since / 1000.0);
  41. _count = (uint64_t)count;
  42. } else {
  43. _count += (uint64_t)count;
  44. }
  45. }
  46. ZT_ALWAYS_INLINE double perSecond(const int64_t now) const
  47. {
  48. double r = 0.0,n = 0.0;
  49. const int64_t since = (now - _ts);
  50. if (since >= ZT_METER_HISTORY_TICK_DURATION) {
  51. r += (double)_count / ((double)since / 1000.0);
  52. n += 1.0;
  53. }
  54. for(int i=0;i<ZT_METER_HISTORY_LENGTH;++i) {
  55. r += _history[i];
  56. n += 1.0;
  57. }
  58. return r / n;
  59. }
  60. private:
  61. volatile double _history[ZT_METER_HISTORY_LENGTH];
  62. volatile int64_t _ts;
  63. volatile uint64_t _count;
  64. AtomicCounter _hptr;
  65. };
  66. } // namespace ZeroTier
  67. #endif