Skip to content

Instantly share code, notes, and snippets.

@grantstephens
Last active February 7, 2017 11:03
Show Gist options
  • Save grantstephens/761557dceca70d15016e6466ad91c081 to your computer and use it in GitHub Desktop.
Save grantstephens/761557dceca70d15016e6466ad91c081 to your computer and use it in GitHub Desktop.
Rate Limiting Decorator that allows bursts
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