Open Model Railroad Network (OpenMRN)
Loading...
Searching...
No Matches
LruCounter.hxx
Go to the documentation of this file.
1
35#ifndef _UTILS_LRUCOUNTER_HXX_
36#define _UTILS_LRUCOUNTER_HXX_
37
38#include <limits>
39
40template <class T> class LruCounter;
41
99{
100public:
104 GlobalLruCounter(unsigned bits_per_bit = 2)
105 : bitsPerBit_(bits_per_bit)
106 {
107 }
108 void tick()
109 {
110 ++tick_;
111 }
112
113private:
114 template <class T> friend class LruCounter;
116 unsigned bitsPerBit_;
119 unsigned tick_ {0};
120};
121
126template <class T> class LruCounter
127{
128public:
130 unsigned value()
131 {
132 return counter_;
133 }
134
138 void tick(const GlobalLruCounter &global)
139 {
140 if (!counter_)
141 {
142 ++counter_;
143 return;
144 }
145 if (counter_ == std::numeric_limits<T>::max())
146 {
147 // Counter is saturated.
148 return;
149 }
150 int nlz = __builtin_clz((unsigned)counter_);
151 int needzero = (32 - nlz) * global.bitsPerBit_;
152 if ((global.tick_ & ((1U << needzero) - 1)) == 0)
153 {
154 ++counter_;
155 }
156 }
157
159 void touch()
160 {
161 counter_ = 0;
162 }
163
164private:
166 T counter_ {0};
167};
168
169#endif // _UTILS_LRUCOUNTER_HXX_
The GlobalLruCounter and a set of LruCounter<> objects cooperate in order to create an approximate LR...
GlobalLruCounter(unsigned bits_per_bit=2)
Constructor.
unsigned bitsPerBit_
Setting defining the exponent.
unsigned tick_
Rolling counter of global ticks.
Create an instance of this type for each object whose age needs to be measured with the GlobalLruCoun...
void tick(const GlobalLruCounter &global)
Increments the local counter.
void touch()
Signals that the object has been used now.
T counter_
Internal counter.
unsigned value()