]>
git.ipfire.org Git - thirdparty/squid.git/blob - src/FadingCounter.cc
2 #include "base/TextException.h"
3 #include "FadingCounter.h"
8 #endif /* HAVE_MATH_H */
10 FadingCounter::FadingCounter(): horizon(-1), precision(10), delta(-1),
13 counters
.reserve(precision
);
14 while (counters
.size() < static_cast<unsigned int>(precision
))
15 counters
.push_back(0);
18 void FadingCounter::clear()
20 for (int i
= 0; i
< precision
; ++i
)
22 lastTime
= current_dtime
;
26 void FadingCounter::configure(double newHorizon
)
28 if (fabs(newHorizon
- horizon
) >= 1e-3) { // diff exceeds one millisecond
29 clear(); // for simplicity
31 delta
= horizon
/ precision
; // may become negative or zero
35 int FadingCounter::count(int howMany
)
40 return total
+= howMany
; // forget nothing
42 if (horizon
< 1e-3) // (e.g., zero)
43 return howMany
; // remember nothing
45 const double deltas
= (current_dtime
- lastTime
) / delta
;
46 if (deltas
>= precision
|| current_dtime
< lastTime
) {
47 clear(); // forget all values
49 // forget stale values, if any
50 // fmod() or "current_dtime/delta" will overflow int for small deltas
51 const int lastSlot
= static_cast<int>(fmod(lastTime
, horizon
) / delta
);
52 const int staleSlots
= static_cast<int>(deltas
);
53 for (int i
= 0, s
= lastSlot
+ 1; i
< staleSlots
; ++i
, ++s
) {
54 const int idx
= s
% precision
;
55 total
-= counters
[idx
];
61 // apply new information
62 lastTime
= current_dtime
;
63 const int curSlot
= static_cast<int>(fmod(lastTime
, horizon
) / delta
);
64 counters
[curSlot
% precision
] += howMany
;