[关闭]
@leaveye 2022-03-22T06:10:10.000000Z 字数 1718 阅读 318

代码样本

代码 样本 速度


SpeedEstimator

  1. class SpeedEstimator {
  2. constexpr static const float epsilon = 1E-24;
  3. constexpr static const float duration_default_multiplier = 50;
  4. using timeValue = uint64_t;
  5. public:
  6. SpeedEstimator() : SpeedEstimator(0) {}
  7. explicit SpeedEstimator(timeValue now, timeValue interval = 20, timeValue mean_duration = 0) {
  8. init(now, interval, mean_duration);
  9. }
  10. void init(timeValue now, timeValue interval, timeValue mean_duration) {
  11. _ts_state = now, _interval = interval;
  12. _n = 0, _d = epsilon;
  13. if (mean_duration != 0) _decay = 1 - interval / (float) mean_duration;
  14. else _decay = 1 - 1 / duration_default_multiplier;
  15. _duration = interval / (1 - _decay);
  16. }
  17. void reset(timeValue now) {
  18. init(now, _interval, _duration);
  19. }
  20. timeValue duration() const {
  21. return (timeValue) std::lround(_duration);
  22. }
  23. float avg() const {
  24. assert(_d >= epsilon || _d <= -epsilon);
  25. return 1000 * _n / _d;
  26. }
  27. void update(timeValue now, size_t size) {
  28. update(now, (float) size);
  29. }
  30. void update(timeValue now, float state) {
  31. auto period = (float) (now - _ts_state);
  32. if (period < _interval) {
  33. _state = state;
  34. } else if (period < _duration + _interval * 4) {
  35. auto stage = state / period * _interval;
  36. while (period >= _interval) {
  37. _d *= _decay, _d += _interval;
  38. _n *= _decay, _n += stage;
  39. state -= stage, period -= _interval;
  40. }
  41. _ts_state = now - period;
  42. _state = state;
  43. } else {
  44. state *= _duration / period;
  45. _d = _duration;
  46. _n = state * (_duration / period);
  47. _ts_state = now;
  48. _state = 0;
  49. }
  50. }
  51. void update(size_t size) {
  52. update((float) size);
  53. }
  54. void update(float state) {
  55. update(_ts_state + _interval, state);
  56. }
  57. void acc(timeValue now, ssize_t count) {
  58. acc(now, (float) count);
  59. }
  60. void acc(timeValue now, float diff) {
  61. update(now, _state + diff);
  62. }
  63. void acc(size_t count) {
  64. acc((float) count);
  65. }
  66. void acc(float diff) {
  67. _state += diff;
  68. }
  69. void accNext(size_t count) {
  70. accNext((float) count);
  71. }
  72. void accNext(float diff) {
  73. update(_state + diff);
  74. }
  75. protected:
  76. float _n = 0, _d = 1E-24;
  77. float _state = 0;
  78. float _decay{};
  79. timeValue _ts_state{}, _interval{};
  80. float _duration{};
  81. };
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注