Last active
February 7, 2017 11:03
-
-
Save grantstephens/761557dceca70d15016e6466ad91c081 to your computer and use it in GitHub Desktop.
Rate Limiting Decorator that allows bursts
This file contains 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
import time | |
def RateLimited(maxPerSecond, burst=1): | |
minInterval = 1.0 / float(maxPerSecond) | |
def decorate(func): | |
firstBurst = [0.0] | |
burstCount = [0] | |
def rateLimitedFunction(*args, **kargs): | |
if burstCount[0] == 0: | |
firstBurst[0] = time.time() | |
if burstCount[0] < burst: | |
burstCount[0] += 1 | |
ret = func(*args, **kargs) | |
if burstCount[0] == burst: | |
burstCount[0] = 0 | |
elapsed = time.time() - firstBurst[0] | |
leftToWait = + burst*minInterval - elapsed | |
if leftToWait > 0: | |
time.sleep(leftToWait) | |
return ret | |
return rateLimitedFunction | |
return decorate | |
@RateLimited(2, 5) | |
def PrintNumber(num): | |
print num | |
if __name__ == "__main__": | |
print "This should print 1,2,3.. at about 2 per second, with bursts of 5" | |
for i in range(1, 100): | |
PrintNumber(i) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment