码迷,mamicode.com
首页 > 其他好文 > 详细

【trick】A variant of token bucket implementation

时间:2018-10-13 00:01:20      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:set   inter   time()   variant   max   get   cap   incr   pre   

 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

标签:set   inter   time()   variant   max   get   cap   incr   pre   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!