diff --git a/src/ripple/basics/DecayingSample.h b/src/ripple/basics/DecayingSample.h index cad097045..37c0ef09e 100644 --- a/src/ripple/basics/DecayingSample.h +++ b/src/ripple/basics/DecayingSample.h @@ -21,7 +21,8 @@ #define RIPPLE_BASICS_DECAYINGSAMPLE_H_INCLUDED #include - +#include + namespace ripple { /** Sampling function using exponential decay to provide a continuous value. @@ -100,6 +101,58 @@ private: time_point m_when; }; +//------------------------------------------------------------------------------ + +/** Sampling function using exponential decay to provide a continuous value. + @tparam HalfLife The half life of a sample, in seconds. +*/ +template +class DecayWindow +{ +public: + using time_point = typename Clock::time_point; + + explicit + DecayWindow (time_point now) + : value_(0) + , when_(now) + { + } + + void + add (double value, time_point now) + { + decay(now); + value_ += value; + } + + double + value (time_point now) + { + decay(now); + return value_ / HalfLife; + } + +private: + static_assert(HalfLife > 0, + "half life must be positive"); + + void + decay (time_point now) + { + if (now <= when_) + return; + using namespace std::chrono; + auto const elapsed = + duration(now - when_).count(); + value_ *= std::pow(2.0, - elapsed / HalfLife); + when_ = now; + } + + double value_; + time_point when_; +}; + } #endif