]>
git.ipfire.org Git - thirdparty/squid.git/blob - src/FadingCounter.cc
2 * Copyright (C) 1996-2015 The Squid Software Foundation and contributors
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
10 #include "base/TextException.h"
11 #include "FadingCounter.h"
12 #include "SquidTime.h"
16 FadingCounter::FadingCounter(): horizon(-1), precision(10), delta(-1),
19 counters
.reserve(precision
);
20 while (counters
.size() < static_cast<unsigned int>(precision
))
21 counters
.push_back(0);
24 void FadingCounter::clear()
26 for (int i
= 0; i
< precision
; ++i
)
28 lastTime
= current_dtime
;
32 void FadingCounter::configure(double newHorizon
)
34 if (fabs(newHorizon
- horizon
) >= 1e-3) { // diff exceeds one millisecond
35 clear(); // for simplicity
37 delta
= horizon
/ precision
; // may become negative or zero
41 int FadingCounter::count(int howMany
)
46 return total
+= howMany
; // forget nothing
48 if (horizon
< 1e-3) // (e.g., zero)
49 return howMany
; // remember nothing
51 const double deltas
= (current_dtime
- lastTime
) / delta
;
52 if (deltas
>= precision
|| current_dtime
< lastTime
) {
53 clear(); // forget all values
55 // forget stale values, if any
56 // fmod() or "current_dtime/delta" will overflow int for small deltas
57 const int lastSlot
= static_cast<int>(fmod(lastTime
, horizon
) / delta
);
58 const int staleSlots
= static_cast<int>(deltas
);
59 for (int i
= 0, s
= lastSlot
+ 1; i
< staleSlots
; ++i
, ++s
) {
60 const int idx
= s
% precision
;
61 total
-= counters
[idx
];
67 // apply new information
68 lastTime
= current_dtime
;
69 const int curSlot
= static_cast<int>(fmod(lastTime
, horizon
) / delta
);
70 counters
[curSlot
% precision
] += howMany
;