Last active
August 29, 2015 14:23
-
-
Save Turin86/6e9f8cbbae81385fa3d2 to your computer and use it in GitHub Desktop.
Small Python class for generic throttling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from datetime import datetime | |
class RateLimiter: | |
def __init__(self, seconds=1): | |
self.count = 0 | |
self.last_time = datetime.now() | |
self.seconds = float(seconds) | |
self.step = 1 | |
def stepping(self): | |
self.count += 1 | |
if self.count % self.step == 0: | |
now = datetime.now() | |
factor = self.seconds / (now - self.last_time).total_seconds() | |
factor = ((factor - 1) / 5) + 1 # Hardcoded smoothness: 5 | |
self.step = int(self.step * factor) | |
if self.step < 1: self.step = 1 | |
self.last_time = now | |
return True | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It is much cheaper to evaluate "self.count % self.step" than requesting the date and comparing. The gist here is to compute a step value which absorbs peaks.