52#include "extensions/qtokenbucket.h"
58#include "utilities/qtime.h"
63static void refill_tokens(qtokenbucket_t *bucket);
78 memset(bucket, 0,
sizeof(qtokenbucket_t));
79 bucket->tokens = init_tokens;
80 bucket->max_tokens = max_tokens;
81 bucket->tokens_per_sec = tokens_per_sec;
94 refill_tokens(bucket);
95 if (bucket->tokens < tokens) {
98 bucket->tokens -= tokens;
110 refill_tokens(bucket);
111 if (bucket->tokens >= tokens) {
114 int tokens_needed = tokens - (int)bucket->tokens;
115 double estimate_milli = (1000 * tokens_needed) / bucket->tokens_per_sec;
116 estimate_milli += ((1000 * tokens_needed) % bucket->tokens_per_sec) ? 1 : 0;
117 return estimate_milli;
124static void refill_tokens(qtokenbucket_t *bucket) {
126 if (bucket->tokens < bucket->max_tokens) {
127 double new_tokens = (now - bucket->last_fill) * 0.001
128 * bucket->tokens_per_sec;
130 ((bucket->tokens + new_tokens) < bucket->max_tokens) ?
131 (bucket->tokens + new_tokens) : bucket->max_tokens;
133 bucket->last_fill = now;
long qtime_current_milli(void)
Returns the current time in milliseconds.
long qtokenbucket_waittime(qtokenbucket_t *bucket, int tokens)
Get the estimate time until given number of token is ready.
void qtokenbucket_init(qtokenbucket_t *bucket, int init_tokens, int max_tokens, int tokens_per_sec)
Initialize the token bucket.
bool qtokenbucket_consume(qtokenbucket_t *bucket, int tokens)
Consume tokens from the bucket.