From 0a36c669c6cbac2ffdd1a47543e0fad8532294c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nils=20O=2E=20Sel=C3=A5sdal?= Date: Tue, 15 Oct 2013 21:35:10 +0200 Subject: [PATCH] More ratelimit optimizations --- include/ucore/rate_limit.h | 4 ++-- src/rate_limit.c | 15 ++++++++------- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/include/ucore/rate_limit.h b/include/ucore/rate_limit.h index 10bd00f..6e9ff42 100644 --- a/include/ucore/rate_limit.h +++ b/include/ucore/rate_limit.h @@ -34,7 +34,7 @@ * * uc_ratelimit_init(&r,20, 1, time(NULL)); * - * NOTE. 2 * (period + 1) * tickets * tickets must not exceed the range of the RateLimit.funds + * NOTE. (period + 1) * tickets must not exceed the range of the RateLimit.funds * * for (;;) { * int fd = accept(..); @@ -67,7 +67,7 @@ struct RateLimit { * Initialize a struct RateLimit, which can hand out @tickets per @period * the perioid must be in the same units as the current_ts * - * NOTE. 2 * (period + 1) * tickets * tickets must not exceed the range of the RateLimit.funds + * NOTE. 2 * (period + 1) * tickets must not exceed the range of the RateLimit.funds * * @param r RateLimit to initialize * @param tickets number of tickets (bucket depth) diff --git a/src/rate_limit.c b/src/rate_limit.c index 2ca92ae..9bb51d0 100644 --- a/src/rate_limit.c +++ b/src/rate_limit.c @@ -5,11 +5,7 @@ void uc_ratelimit_init(struct RateLimit *r, long tickets, long period, long curr { r->tickets = tickets; - if (tickets > period) { - r->ticket_cost = tickets * period; - } else { - r->ticket_cost = period; - } + r->ticket_cost = period; r->period = period; r->funds = r->ticket_cost * tickets; @@ -48,8 +44,13 @@ int uc_ratelimit_allow(struct RateLimit *r, long current_ts) //Calculate the cost of tickets that became available since //the last time. - r->funds += diff_period * - ((r->tickets * r->ticket_cost) / r->period); + r->funds += diff_period * r->tickets; + + //the below is the real algorithm, with ticket_cost = + //tickets * period. + //we have optimized this to the expression used above + //r->funds += diff_period * + // ((r->tickets * r->ticket_cost) / r->period); //throttle handing out tickets if (r->funds > r->ticket_cost * r->tickets) {