License New BSD license
Lines 50
Keywords
iteration (1) percent (1) print (6)
Permissions
Viewable by Everyone
Editable by All Siafoo Users

Print Percent-Done Statements at Regular Intervals Atom Feed 0

In Brief A better way to report how far done your iterative process is. You can report percent-done statements at regular frequencies (in time), intervals (in percent), or just at the start and end of iterations.... more
# 's
 1# Copyright 2007 Regents of the University of California
2# Written by David Isaacson at the University of California
3# BSD License
4
5import time
6
7class PercentPrint:
8 """
9 A simple helper to print out percentage-done statements every so often.
10 Call on every iteration, will only print when necessary.
11 """
12 def __init__(self, total, interval=10, frequency=0, indent=""):
13 """
14 The only required argument is 'total', the number of iterations
15 you will be doing. You may also specify an interval (in percent)
16 and/or a frequency (in time) that you would like to see print-outs.
17 Setting either to 0 will disable that mode. Setting both to 0 will
18 print only 0% and 100% statements. 'indent' will be prepended to
19 every print statement."
20 """
21 self.total = total
22 self.interval = interval
23 self.frequency = frequency
24 self.indent = indent
25 self.Reset()
26
27 def __call__(self,value):
28 """
29 Checks the value of the current iteration to see if print-outs are
30 needed. Prints if necessary.
31 """
32 current = value / self.total * 100
33 if self.frequency: clock = time.clock()
34
35 if numpy.round(2*current - self.last,12) >= 100.0: print self.indent + "100% done."
36 elif (self.interval and current//self.interval > self.previous//self.interval) \
37 or (self.frequency and (clock - self.prevtime) > self.frequency) \
38 or current == 0:
39
40 print self.indent + "%d%% done." %(numpy.round(current))
41
42 if self.interval: self.previous = current
43 if self.frequency: self.prevtime = clock
44
45 self.last = current
46
47 def Reset(self):
48 """
49 Resets the class. Call this to start over.
50 """
51 self.previous = 0.0
52 self.prevtime = 0.0
53 self.last = 0.0

A better way to report how far done your iterative process is. You can report percent-done statements at regular frequencies (in time), intervals (in percent), or just at the start and end of iterations.

Initialize this class with the total number of iterations, and call your object with the current iteration count whenever you think you might want to print something out (usually every iteration). For more information, check out the docstrings.

Comments

over 8 years ago (29 Mar 2008 at 04:46 AM) by Stou S.
You know there is an actual 'NumPy' lexer right? Also can you make this thing print on the same line?
over 8 years ago (29 Mar 2008 at 01:29 PM) by David Isaacson
What does NumPy have to do with this? And no, there's no option to have it print on the same line because I was too lazy to look up how... but feel free to add it!