]>
Commit | Line | Data |
---|---|---|
582c2af2 | 1 | #include "squid.h" |
8277060a | 2 | #include "base/TextException.h" |
8277060a | 3 | #include "FadingCounter.h" |
602d9612 | 4 | #include "SquidTime.h" |
8277060a | 5 | |
074d6a40 | 6 | #include <cmath> |
582c2af2 | 7 | |
8277060a | 8 | FadingCounter::FadingCounter(): horizon(-1), precision(10), delta(-1), |
a459e80a | 9 | lastTime(0), total(0) |
8277060a CT |
10 | { |
11 | counters.reserve(precision); | |
12 | while (counters.size() < static_cast<unsigned int>(precision)) | |
13 | counters.push_back(0); | |
14 | } | |
15 | ||
16 | void FadingCounter::clear() | |
17 | { | |
18 | for (int i = 0; i < precision; ++i) | |
19 | counters[i] = 0; | |
20 | lastTime = current_dtime; | |
21 | total = 0; | |
22 | } | |
23 | ||
24 | void FadingCounter::configure(double newHorizon) | |
25 | { | |
26 | if (fabs(newHorizon - horizon) >= 1e-3) { // diff exceeds one millisecond | |
27 | clear(); // for simplicity | |
28 | horizon = newHorizon; | |
29 | delta = horizon / precision; // may become negative or zero | |
30 | } | |
31 | } | |
32 | ||
33 | int FadingCounter::count(int howMany) | |
34 | { | |
35 | Must(howMany >= 0); | |
36 | ||
37 | if (delta < 0) | |
38 | return total += howMany; // forget nothing | |
39 | ||
40 | if (horizon < 1e-3) // (e.g., zero) | |
41 | return howMany; // remember nothing | |
42 | ||
43 | const double deltas = (current_dtime - lastTime) / delta; | |
44 | if (deltas >= precision || current_dtime < lastTime) { | |
45 | clear(); // forget all values | |
46 | } else { | |
47 | // forget stale values, if any | |
48 | // fmod() or "current_dtime/delta" will overflow int for small deltas | |
49 | const int lastSlot = static_cast<int>(fmod(lastTime, horizon) / delta); | |
50 | const int staleSlots = static_cast<int>(deltas); | |
51 | for (int i = 0, s = lastSlot + 1; i < staleSlots; ++i, ++s) { | |
52 | const int idx = s % precision; | |
53 | total -= counters[idx]; | |
54 | counters[idx] = 0; | |
55 | Must(total >= 0); | |
56 | } | |
57 | } | |
58 | ||
59 | // apply new information | |
60 | lastTime = current_dtime; | |
61 | const int curSlot = static_cast<int>(fmod(lastTime, horizon) / delta); | |
62 | counters[curSlot % precision] += howMany; | |
63 | total += howMany; | |
64 | Must(total >= 0); | |
65 | ||
66 | return total; | |
67 | } |