Last active
January 8, 2021 18:53
-
-
Save alexshpilkin/f8acad98e89ce6edc8d0c832380a38e3 to your computer and use it in GitHub Desktop.
Rate-limiting utility for tracing and such
This file contains 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
#!/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