Implementation when you want to stop processing for a certain period of time in Python.
When calling an external API many times in a for statement, you may want to leave a certain interval. But it's a little inefficient if you always put a certain amount of sleep. I want to put sleep if the processing time is less than a certain interval.
Example) I want to leave an interval of 2 seconds or more between requests to the Twitter API.
import time
from datetime import datetime
def hoge():
start = datetime.now()
#Here API request and related processing
hoge()
exec_time = (datetime.now() - start).microseconds
#If the process does not take more than 2 seconds, sleep for a minimum of 2 seconds
sleep_sec = float(2000 - exec_time) / 1000
if sleep_sec > 0:
time.sleep(sleep_sec)
There seems to be a better way to write it.