Created
January 16, 2014 22:18
-
-
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.
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
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