Project

General

Profile

1 981 aaronmk
# Profiling: Times operations and provides the user with statistical information
2
3
import sys
4
import datetime
5
6 989 aaronmk
import format
7 981 aaronmk
8
def now(): return datetime.datetime.now()
9
10
class Profiler:
11
    def __init__(self, start_now=False):
12
        self.total = datetime.timedelta()
13
        if start_now: self.start()
14
15
    def start(self): self.start = now()
16
17
    def stop(self):
18
        assert self.start != None
19
        self.total += now() - self.start
20
21
    def msg(self): return 'Took '+str(self.total)+' sec'
22
23
class ItersProfiler(Profiler):
24
    def __init__(self, iter_text='iteration', **settings):
25
        Profiler.__init__(self, **settings)
26
        self.iter_text = iter_text
27
        self.iter_ct = None
28
29
    def add_iters(self, iter_ct):
30
        if self.iter_ct == None: self.iter_ct = 0
31
        self.iter_ct += iter_ct
32
33
    def stop(self, iter_ct=None):
34
        Profiler.stop(self)
35
        if iter_ct != None: self.add_iters(iter_ct)
36
37
    def msg(self):
38
        msg = Profiler.msg(self)
39
        if self.iter_ct != None:
40 989 aaronmk
            msg += ('/'+format.int2str(self.iter_ct)+' '+self.iter_text+'(s) = '
41
            +format.to_si(float(self.total.total_seconds())/self.iter_ct)
42 981 aaronmk
            +'s/'+self.iter_text)
43
        return msg