hmbdc
simplify-high-performance-messaging-programming
Rater.hpp
1 #include "hmbdc/Copyright.hpp"
2 #pragma once
3 
4 #include "hmbdc/Exception.hpp"
5 #include "hmbdc/time/Time.hpp"
6 
7 #include <iostream>
8 #include <stdexcept>
9 
10 namespace hmbdc { namespace time {
11 using namespace hmbdc;
12 using namespace hmbdc::time;
13 struct Rater {
14  Rater()
15  : drop_()
16  , bucket_()
17  , currentLevel_()
18  , previousCheck_()
19  , enabled_(false)
20  {}
21 
22  Rater(Duration duration, size_t times, size_t burst, bool enabled = true)
23  : drop_(duration / (times?times:1ul))
24  , bucket_(drop_ * burst)
25  , currentLevel_(bucket_)
26  , previousCheck_()
27  , enabled_(enabled?times != 0:false)
28  {}
29 
30  bool check(size_t n = 1u) {
31  if (!enabled_) return true;
32  n_ = n;
33  auto now = SysTime::now();
34  currentLevel_ += now - previousCheck_;
35  previousCheck_ = now;
36  if (currentLevel_ > bucket_) currentLevel_ = bucket_;
37  return currentLevel_ >= drop_ * n;
38  }
39 
40  void commit() {
41  currentLevel_ -= drop_ * n_;
42  }
43 
44 private:
45  Duration drop_;
46  Duration bucket_;
47  Duration currentLevel_;
48  SysTime previousCheck_;
49  bool enabled_;
50  size_t n_;
51 };
52 }}
Definition: Time.hpp:15
Definition: Time.hpp:118
Definition: Rater.hpp:10
Definition: Rater.hpp:13
Definition: Client.hpp:11