Ref T184 Minor optimization in CTokenBucket: avoid converting interval to seconds

every time a token is consumed, by doing the conversion once in the constructor.
This commit is contained in:
Mathew Sutcliffe
2017-11-08 21:30:16 +00:00
parent 23becf9619
commit 2f54e00d65
2 changed files with 3 additions and 3 deletions

View File

@@ -17,7 +17,7 @@ using namespace BlackMisc::PhysicalQuantities;
namespace BlackMisc
{
CTokenBucket::CTokenBucket(int capacity, const CTime &interval, int numTokensToRefill)
: m_capacity(capacity), m_interval(interval), m_numTokensToRefill(numTokensToRefill) {}
: m_capacity(capacity), m_intervalSecs(interval.value(CTimeUnit::s())), m_numTokensToRefill(numTokensToRefill) {}
bool CTokenBucket::tryConsume(int numTokens)
{
@@ -52,7 +52,7 @@ namespace BlackMisc
{
const auto now = QDateTime::currentDateTime();
const auto deltaSeconds = m_lastReplenishmentTime.secsTo(now);
const int numberOfTokens = static_cast<int>(m_numTokensToRefill * deltaSeconds / m_interval.value(CTimeUnit::s()));
const int numberOfTokens = static_cast<int>(m_numTokensToRefill * deltaSeconds / m_intervalSecs);
// Update the time only when replenishment actually took place. We will end up in a infinite loop otherwise.
if (numberOfTokens > 0) { m_lastReplenishmentTime = now; }

View File

@@ -47,7 +47,7 @@ namespace BlackMisc
int m_capacity = 10; //!< Maximum capacity of tokens
int m_availableTokens = 10; //!< Currently available tokens. The initial value is 10
PhysicalQuantities::CTime m_interval; //!< Refill interval, e.g. every 5 secs
double m_intervalSecs = 5; //!< Refill interval, e.g. every 5 secs
int m_numTokensToRefill; //!< Number of tokens to be refilled each interval
QDateTime m_lastReplenishmentTime = QDateTime::currentDateTime(); //!< Last time
};