Instantly share code, notes, and snippets.

Embed
What would you like to do?
#!/usr/bin/env python3
"""Generate data at constant rate (float interval).
To try, run:
$ python3 constant-bit-rate-modulo.py | pv >/dev/null
"""
from time import sleep, monotonic as timer
chunksize, interval = 1024, 0.03125 # 32KiB/s
chunk = 'x' * chunksize
while True:
# assume print(chunk) takes less than interval seconds
sleep(interval - timer() % interval) # use modulo to support float interval
print(chunk)
#!/usr/bin/env python3
"""Generate data at constant rate.
To try, run:
$ python3 constant-bit-rate.py | pv >/dev/null
"""
from time import sleep, monotonic as timer
chunksize = 1 << 15 # 32K
interval = 1 # per second
chunk = 'x' * chunksize
deadline = timer()
while True:
deadline += interval
print(chunk)
delay = deadline - timer()
if delay > 0:
sleep(delay)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment