Project

General

Profile

1
# Profiling: Times operations and provides the user with statistical information
2

    
3
import sys
4
import datetime
5

    
6
import dates
7
import format
8

    
9
class Profiler:
10
    def __init__(self, start_now=False):
11
        self.total = datetime.timedelta()
12
        if start_now: self.start()
13
    
14
    def add_time(self, time): self.total += time
15
    
16
    def start(self): self.start_ = dates.now()
17
    
18
    def stop(self):
19
        assert self.start_ != None
20
        self.add_time(dates.now() - self.start_)
21
    
22
    def msg(self): return 'Took '+str(self.total)+' sec'
23
    
24
    def add_subprofiler(self, profiler):
25
        '''for use with cumulative profilers'''
26
        self.add_time(profiler.total)
27

    
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
        if self.iter_ct != None and self.iter_ct > 0:
45
            msg += ('/'+format.int2str(self.iter_ct)+' '+self.iter_text+'(s) = '
46
            +format.to_si(float(dates.total_seconds(self.total))/self.iter_ct)
47
            +'s/'+self.iter_text)
48
        return msg
49
    
50
    def add_subprofiler(self, profiler):
51
        Profiler.add_subprofiler(self, profiler)
52
        self.add_iters(profiler.iter_ct)
(31-31/49)