Skip to content

Instantly share code, notes, and snippets.

@davidalber
Created January 16, 2014 22:18
Show Gist options
  • Save davidalber/8464584 to your computer and use it in GitHub Desktop.
Save davidalber/8464584 to your computer and use it in GitHub Desktop.
Decorator to limit the maximum number of times a function will run per second.
def max_per_second(mps):
def decorate(func):
ind = [0]
arr = [0.0]*mps
def wrapper(*args, **kwargs):
now = time.time()
stime = (arr[ind[0]]+1) - now
if stime > 0:
time.sleep(stime)
arr[ind[0]] = time.time()
ind[0] = (ind[0] + 1) % mps
return func(*args, **kwargs)
return wrapper
return decorate
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment