Skip to content

Instantly share code, notes, and snippets.

@beltiras
Last active August 27, 2023 02:45
Show Gist options
  • Save beltiras/86294a3e746820e421080b1619b0df46 to your computer and use it in GitHub Desktop.
Save beltiras/86294a3e746820e421080b1619b0df46 to your computer and use it in GitHub Desktop.
import time
import datetime
def timing_protect(constant_time):
"""
The jitter will depend not on runtime but activity on the system writ large
"""
def _deco(func):
def _wrapped(*args, **kwargs):
start = datetime.datetime.now()
res = func(*args, **kwargs)
sleeptime = float(constant_time) - (datetime.datetime.now() - start).total_seconds
while sleeptime < 0: # unless timing has considerably changed, this should be fine
sleeptime += constant_time
time.sleep(sleeptime)
return res
return _wrapped
return _deco
def autostat_timing_protect(weighting_time, min_samples, multiple=10.0):
"""
This can be set to algorithmic timing all the time by setting min_samples to 0
weighting_time is the time used while getting good sampling. Multiple is the acceptable
cost to the function. Default set to 10.0 for a large enough margin. 2.0 is probably too low.
"""
total_time = 0.0f
number_of_runs = 0
def _deco(func):
def _wrapped(*args, **kwargs):
start = datetime.datetime.now()
res = func(*args, **kwargs)
runtime = (datetime.datetime.now() - start).total_seconds
number_of_runs += 1
total_time += runtime
ave_time = total_time / float(number_of_runs)
sleeptime = (round(ave_time, round(math.log10(ave_time))) * multiple) - runtime
if min_samples > number_of_runs:
sleeptime = weighting_time - runtime
if sleeptime < 0:
sleeptime += (round(math.abs(sleeptime / weighting_time))* weighting_time)
time.sleep(sleeptime)
return res
return _wrapped
return _deco
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment