import time
from functools import wraps
def rate_limiter(max_calls, period=60):
def decorator(func):
timestamps = []
@wraps(func)
def wrapper(*args, **kwargs):
nonlocal timestamps
current_time = time.time()
# Remove timestamps outside of the current period
timestamps = [t for t in timestamps if current_time - t < period]
if len(timestamps) < max_calls:
timestamps.append(current_time)
return func(*args, **kwargs)
else:
print(f"Rate limit exceeded. Try again in {int(period - (current_time - timestamps[0]))} seconds.")
return wrapper
return decorator
# Example usage:
@rate_limiter(max_calls=5)
def my_function():
# Your function implementation here
print("Function is called")
# Test the rate limiter
for i in range(10):
my_function()
time.sleep(1) # Sleep for demonstration purposes