Mercurial > prosody-hg
comparison util/throttle.lua @ 8245:9499db96c032
util.throttle: Fix initial time setting (double accounting the first time) and fractional balance updates (0.1*10 was not the same as 1*1)
| author | Waqas Hussain <waqas20@gmail.com> |
|---|---|
| date | Sun, 17 Sep 2017 13:29:14 -0400 |
| parents | dc758422d896 |
| children | 64165865b131 |
comparison
equal
deleted
inserted
replaced
| 8244:6a27e5f276f7 | 8245:9499db96c032 |
|---|---|
| 10 | 10 |
| 11 function throttle:update() | 11 function throttle:update() |
| 12 local newt = gettime(); | 12 local newt = gettime(); |
| 13 local elapsed = newt - self.t; | 13 local elapsed = newt - self.t; |
| 14 self.t = newt; | 14 self.t = newt; |
| 15 local balance = floor(self.rate * elapsed) + self.balance; | 15 local balance = (self.rate * elapsed) + self.balance; |
| 16 if balance > self.max then | 16 if balance > self.max then |
| 17 self.balance = self.max; | 17 self.balance = self.max; |
| 18 else | 18 else |
| 19 self.balance = balance; | 19 self.balance = balance; |
| 20 end | 20 end |
| 38 return false, balance, (cost-balance); | 38 return false, balance, (cost-balance); |
| 39 end | 39 end |
| 40 end | 40 end |
| 41 | 41 |
| 42 local function create(max, period) | 42 local function create(max, period) |
| 43 return setmetatable({ rate = max / period, max = max, t = 0, balance = max }, throttle_mt); | 43 return setmetatable({ rate = max / period, max = max, t = gettime(), balance = max }, throttle_mt); |
| 44 end | 44 end |
| 45 | 45 |
| 46 return { | 46 return { |
| 47 create = create; | 47 create = create; |
| 48 }; | 48 }; |
