Skip to content

Instantly share code, notes, and snippets.

@Turin86
Last active August 29, 2015 14:23
Show Gist options
  • Save Turin86/6e9f8cbbae81385fa3d2 to your computer and use it in GitHub Desktop.
Save Turin86/6e9f8cbbae81385fa3d2 to your computer and use it in GitHub Desktop.
Small Python class for generic throttling
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
@Turin86
Copy link
Author

Turin86 commented Jun 24, 2015

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment