Overte C++ Documentation
RateCounter.h
1 //
2 // Created by Bradley Austin Davis 2016/04/10
3 // Copyright 2013-2016 High Fidelity, Inc.
4 //
5 // Distributed under the Apache License, Version 2.0.
6 // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
7 //
8 
9 #pragma once
10 #ifndef hifi_Shared_RateCounter_h
11 #define hifi_Shared_RateCounter_h
12 
13 #include <stdint.h>
14 #include <atomic>
15 #include <functional>
16 #include <QtCore/QElapsedTimer>
17 
18 #include "../SharedUtil.h"
19 #include "../NumericalConstants.h"
20 
21 template <uint32_t INTERVAL = MSECS_PER_SECOND, uint8_t PRECISION = 2>
22 class RateCounter {
23 public:
24  RateCounter() { _rate = 0; } // avoid use of std::atomic copy ctor
25 
26  void increment(size_t count = 1) {
27  checkRate();
28  _count += count;
29  }
30 
31  float rate() const { checkRate(); return _rate; }
32 
33  uint8_t precision() const { return PRECISION; }
34 
35  uint32_t interval() const { return INTERVAL; }
36 
37 private:
38  mutable uint64_t _expiry { usecTimestampNow() + INTERVAL * USECS_PER_MSEC};
39  mutable size_t _count { 0 };
40  const float _scale { powf(10, PRECISION) };
41  mutable std::atomic<float> _rate;
42 
43  void checkRate() const {
44  auto now = usecTimestampNow();
45  if (now > _expiry) {
46  float MSECS_PER_USEC = 0.001f;
47  float SECS_PER_MSEC = 0.001f;
48  float intervalSeconds = ((float)INTERVAL + (float)(now - _expiry) * MSECS_PER_USEC) * SECS_PER_MSEC;
49  _rate = roundf((float)_count / intervalSeconds * _scale) / _scale;
50  _expiry = now + INTERVAL * USECS_PER_MSEC;
51  _count = 0;
52  };
53  }
54 
55 };
56 
57 #endif