Created
December 25, 2018 08:00
-
-
Save jerryan999/ddb7c7d9540192561b73a66cd2d73e43 to your computer and use it in GitHub Desktop.
限制方法调用频率
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 | |
import threading | |
from functools import wraps | |
def rate_limited(max_per_second): | |
""" | |
Decorator that make functions not be called faster than | |
""" | |
lock = threading.Lock() | |
min_interval = 1.0 / float(max_per_second) | |
def decorate(func): | |
last_time_called = [0.0] | |
@wraps(func) | |
def rate_limited_function(*args, **kwargs): | |
lock.acquire() | |
elapsed = time.clock() - last_time_called[0] | |
left_to_wait = min_interval - elapsed | |
if left_to_wait > 0: | |
time.sleep(left_to_wait) | |
lock.release() | |
ret = func(*args, **kwargs) | |
last_time_called[0] = time.clock() | |
return ret | |
return rate_limited_function | |
return decorate | |
@rate_limited(5) | |
def print_num_wait(num): | |
""" | |
Rate: 5 times per second | |
""" | |
print(num) | |
if __name__ == "__main__": | |
def with_print(func): | |
def decorate(*arg,**kwargs): | |
print() | |
start = time.time() | |
print('Started at:{}'.format(start)) | |
ret = func(*arg,**kwargs) | |
end = time.time() | |
print('Ended at:{}'.format(end)) | |
print('Elapsed:{}'.format(end-start)) | |
return ret | |
return decorate | |
@with_print | |
def rate_5_func(): | |
for i in range(1,11): | |
print_num_wait(i) | |
@with_print | |
def rate_5_func_possible_long(): | |
for i in range(1,11): | |
sleep_wait(i) | |
# attempt #1 | |
rate_5_func() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment