首页 > 其他 > 详细

【trick】A variant of token bucket implementation

时间:2018-10-12 23:28:43      阅读:41      评论:0      收藏:0      [点我收藏+]

标签:capacity   auto   pre   normalize   interval   implement   con   imp   bsp   

 1 struct TokenBucket
 2 {
 3   double fill_interval_;
 4   double gen_interval_;
 5   double reset_time_;
 6   // reset_time_ is equivalent to last_consume_time + token_num and
 7   // the calculated token num is auto renormalized on limit change.
 8   
 9   TokenBucket()
10   : fill_interval_(0.0)
11   , gen_interval_(0.0)
12   , reset_time_(0.0) {}
13   
14   // eg, for 10req/30s, capacity=10, period=30
15   void set_limit(double capacity, double period)
16   {
17     fill_interval_ = period;
18     gen_interval_ = period / capacity;
19   }
20   
21   bool consume(unsigned num)
22   {
23     double curr_time = get_monotonic_time();
24     double new_reset_time = std::max(reset_time_, curr_time - fill_interval_) + gen_interval_ * num;
25     if (curr_time >= new_reset_time)
26     {
27       reset_time_ = new_reset_time; // reset_time_ is monotonic increasing
28       return true;
29     }
30     return false;
31   }
32 };

 

【trick】A variant of token bucket implementation

标签:capacity   auto   pre   normalize   interval   implement   con   imp   bsp   

原文:https://www.cnblogs.com/albumcover/p/9780439.html

(0)
(0)
   
举报
评论 一句话评论(0
0条  
登录后才能评论!
© 2014 bubuko.com 版权所有 鲁ICP备09046678号-4
打开技术之扣,分享程序人生!
             

鲁公网安备 37021202000002号