Skip to content

Instantly share code, notes, and snippets.

@tomislacker
Forked from gregburek/rateLimitDecorator.py
Created July 17, 2019 12:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomislacker/383234a26a81dff6ead52da3b6dbc8c9 to your computer and use it in GitHub Desktop.
Save tomislacker/383234a26a81dff6ead52da3b6dbc8c9 to your computer and use it in GitHub Desktop.
Rate limiting function calls with Python Decorators
import time
def RateLimited(maxPerSecond):
minInterval = 1.0 / float(maxPerSecond)
def decorate(func):
lastTimeCalled = [0.0]
def rateLimitedFunction(*args,**kargs):
elapsed = time.clock() - lastTimeCalled[0]
leftToWait = minInterval - elapsed
if leftToWait>0:
time.sleep(leftToWait)
ret = func(*args,**kargs)
lastTimeCalled[0] = time.clock()
return ret
return rateLimitedFunction
return decorate
@RateLimited(2) # 2 per second at most
def PrintNumber(num):
print num
if __name__ == "__main__":
print "This should print 1,2,3... at about 2 per second."
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