Created
December 7, 2023 20:02
-
-
Save devrim/fdfada5aa80501b39b96f20810a51a6e to your computer and use it in GitHub Desktop.
python throttling
This file contains hidden or 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 | |
def create_throttled_function(func, period): | |
"""Creates a throttled version of the given function that can only be called once every 'period' seconds.""" | |
last_called = [0] | |
def throttled_function(*args, **kwargs): | |
nonlocal last_called | |
current_time = time.time() | |
if current_time - last_called[0] >= period: | |
last_called[0] = current_time | |
return func(*args, **kwargs) | |
return throttled_function | |
# Example usage | |
def my_function(): | |
print("Function is called") | |
throttled_my_function = create_throttled_function(my_function, 2) | |
# Testing the throttled function | |
throttled_my_function() # This call will work | |
time.sleep(1) | |
throttled_my_function() # This call will be ignored since it's within 2 seconds of the last call | |
time.sleep(2) | |
throttled_my_function() # This call will work, as it's 2 seconds after the last call |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment