Skip to content

Instantly share code, notes, and snippets.

@pwyliu
Forked from gregburek/rateLimitDecorator.py
Last active August 29, 2015 13:58
Show Gist options
  • Save pwyliu/9948465 to your computer and use it in GitHub Desktop.
Save pwyliu/9948465 to your computer and use it in GitHub Desktop.
import time
def rate_limited(max_rate):
"""
max_rate is in seconds
"""
min_interval = 1.0 / float(max_rate)
def decorate(func):
last_time_called = [0.0]
def rate_limited_function(*args, **kargs):
elapsed = time.clock() - last_time_called[0]
left_to_wait = min_interval - elapsed
if left_to_wait > 0:
time.sleep(left_to_wait)
ret = func(*args, **kargs)
last_time_called[0] = time.clock()
return ret
return rate_limited_function
return decorate
@rate_limited(5)
def print_number(num):
print num
if __name__ == "__main__":
print "This should print 1,2,3... at about 2 per second."
for i in range(1, 100):
print_number(i)
@pwyliu
Copy link
Author

pwyliu commented Apr 3, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment