Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Progress Counter in Python - wrote it before discovering tqdm
from typing import List
from datetime import datetime, timedelta
class PercentageCounter:
"""Counter for stepping percentages over an arbitrary number
e.g. total = 10, step = 0.15 (15%)
counter.next(1) # progress is 10%, returns nothing
counter.next(2) # progress is 20%, returns 15
counter.next(3) # progress is 30%, returns nothing (has to exceed step)
counter.next(4) # progress is 40%, returns 30
"""
def __init__(self, total, step=0.01):
self.total = total
self.step = step
self.current = 0
self.previous_date = None
self.time_diff_avg = timedelta()
def next_percentage(self, progress) -> List[str]:
if self.previous_date:
weighted_avg = 5
new_diff = datetime.utcnow() - self.previous_date
new_total = self.time_diff_avg * (weighted_avg - 1) + new_diff
self.time_diff_avg = new_total / weighted_avg
self.previous_date = datetime.utcnow()
percentage = progress / self.total
done = []
while self.current + self.step < percentage:
self.current += self.step
eta = self.time_diff_avg * (self.total - progress)
done.append(f"{round(self.current * 100):02}% Done... (ETA {eta})")
return done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment