Skip to content

Instantly share code, notes, and snippets.

@mintyPT
Last active August 20, 2024 09:53
Show Gist options
  • Save mintyPT/162a6fe9ca9ed3969cd47db5f98c0aa3 to your computer and use it in GitHub Desktop.
Save mintyPT/162a6fe9ca9ed3969cd47db5f98c0aa3 to your computer and use it in GitHub Desktop.
Class to help you keep track of the progress of a loop
import time
from datetime import timedelta
class ProgressList:
def __init__(self, data, step=1, description=None, eta=True):
self.data = data
self.total = len(data)
self.current_index = 0
self.step = step # Step interval for printing progress
self.start_time = None
self.description = description
self.eta = eta
def __iter__(self):
self.current_index = 0 # Reset the counter when iteration begins
self.start_time = time.time() # Record the start time
return self
def __next__(self):
if self.current_index < self.total:
item = self.data[self.current_index]
self.current_index += 1
if self.current_index % self.step == 0 or self.current_index == self.total:
self.print_progress()
return item
else:
raise StopIteration
def print_progress(self):
progress = (self.current_index / self.total) * 100
elapsed_time = time.time() - self.start_time
estimated_total_time = elapsed_time / self.current_index * self.total if self.current_index > 0 else 0
eta = estimated_total_time - elapsed_time
eta_formatted = str(timedelta(seconds=int(eta)))
if self.description:
result = f"Progress ({self.description}): {progress:.2f}%"
else:
result = f"Progress: {progress:.2f}%"
if self.eta:
result += f", ETA: {eta_formatted}"
print(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment