Last active
April 8, 2022 07:36
-
-
Save timgianitsos/92101d6de8e9889effaa3ea2edd585e9 to your computer and use it in GitHub Desktop.
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
from time import time, sleep | |
__author__ = 'Tim Gianitsos' | |
class Stopwatch: | |
''' | |
Display loop progress | |
Wrap an iterable object, and obtain automatic updates on the progress of iteration. | |
Example: | |
Replace `for i in range(15):` with `for i in Stopwatch(range(15)):` | |
That's it! The `Stopwatch` will display information about the progress of the loop. | |
''' | |
def __init__(self, iterable): | |
self.iterable = tuple(iterable) | |
def __iter__(self): | |
start_time = time() | |
num_iters = len(self.iterable) | |
for i, val in enumerate(self.iterable): | |
yield val | |
cur_time = time() | |
elapsed = cur_time - start_time | |
i = i + 1 #consider having already completed the iteration | |
print( | |
f'Progress: {i / num_iters * 100:.2f}%, ' | |
f'Elapsed: {elapsed:.2f} sec, ' | |
f'Estimated remaining: {elapsed * (num_iters - i) / i:.2f} sec', | |
end='\r' | |
) | |
print() | |
def main(): | |
for _ in Stopwatch(range(10)): | |
sleep(0.5) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment