Skip to content

Instantly share code, notes, and snippets.

@alexshpilkin
Last active January 8, 2021 18:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexshpilkin/f8acad98e89ce6edc8d0c832380a38e3 to your computer and use it in GitHub Desktop.
Save alexshpilkin/f8acad98e89ce6edc8d0c832380a38e3 to your computer and use it in GitHub Desktop.
Rate-limiting utility for tracing and such
#!/usr/bin/env python3
from time import monotonic
class periodically:
def __init__(self, interval):
self.interval = interval
self._previous = None
def __enter__(self):
if self._previous is not None:
raise RuntimeError
self._previous = monotonic()
return self
def __bool__(self):
if self._previous is None:
raise RuntimeError
now = monotonic(); elapsed = now - self._previous
if elapsed >= self.interval:
self._previous = now - elapsed % self.interval
return True
else:
return False
def __exit__(self, exc_type, exc_value, exc_tb):
if self._previous is None:
raise RuntimeError
self._previous = None
if __name__ == '__main__': # test and demonstration
from time import sleep
with periodically(2) as trace:
start = monotonic()
for i in range(20):
sleep(.75)
if trace: print(i, monotonic() - start)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment