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 1042 aaronmk
    def start(self): self.start = dates.now()
15 981 aaronmk
16
    def stop(self):
17
        assert self.start != None
18 1042 aaronmk
        self.total += dates.now() - self.start
19 981 aaronmk
20
    def msg(self): return 'Took '+str(self.total)+' sec'
21
22
class ItersProfiler(Profiler):
23
    def __init__(self, iter_text='iteration', **settings):
24
        Profiler.__init__(self, **settings)
25
        self.iter_text = iter_text
26
        self.iter_ct = None
27
28
    def add_iters(self, iter_ct):
29
        if self.iter_ct == None: self.iter_ct = 0
30
        self.iter_ct += iter_ct
31
32
    def stop(self, iter_ct=None):
33
        Profiler.stop(self)
34
        if iter_ct != None: self.add_iters(iter_ct)
35
36
    def msg(self):
37
        msg = Profiler.msg(self)
38
        if self.iter_ct != None:
39 989 aaronmk
            msg += ('/'+format.int2str(self.iter_ct)+' '+self.iter_text+'(s) = '
40 1042 aaronmk
            +format.to_si(float(dates.total_seconds(self.total))/self.iter_ct)
41 981 aaronmk
            +'s/'+self.iter_text)
42
        return msg