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 1042 aaronmk
import dates
7 989 aaronmk
import format
8 981 aaronmk
9
class Profiler:
10
    def __init__(self, start_now=False):
11
        self.total = datetime.timedelta()
12
        if start_now: self.start()
13
14 9523 aaronmk
    def add_time(self, time): self.total += time
15
16 5104 aaronmk
    def start(self): self.start_ = dates.now()
17 981 aaronmk
18
    def stop(self):
19 5104 aaronmk
        assert self.start_ != None
20 9523 aaronmk
        self.add_time(dates.now() - self.start_)
21 981 aaronmk
22
    def msg(self): return 'Took '+str(self.total)+' sec'
23 9524 aaronmk
24
    def add_subprofiler(self, profiler):
25
        '''for use with cumulative profilers'''
26
        self.add_time(profiler.total)
27 981 aaronmk
28
class ItersProfiler(Profiler):
29
    def __init__(self, iter_text='iteration', **settings):
30
        Profiler.__init__(self, **settings)
31
        self.iter_text = iter_text
32
        self.iter_ct = None
33
34
    def add_iters(self, iter_ct):
35
        if self.iter_ct == None: self.iter_ct = 0
36
        self.iter_ct += iter_ct
37
38
    def stop(self, iter_ct=None):
39
        Profiler.stop(self)
40
        if iter_ct != None: self.add_iters(iter_ct)
41
42
    def msg(self):
43
        msg = Profiler.msg(self)
44 1648 aaronmk
        if self.iter_ct != None and self.iter_ct > 0:
45 989 aaronmk
            msg += ('/'+format.int2str(self.iter_ct)+' '+self.iter_text+'(s) = '
46 1042 aaronmk
            +format.to_si(float(dates.total_seconds(self.total))/self.iter_ct)
47 981 aaronmk
            +'s/'+self.iter_text)
48
        return msg
49 9524 aaronmk
50
    def add_subprofiler(self, profiler):
51
        Profiler.add_subprofiler(self, profiler)
52
        self.add_iters(profiler.iter_ct)