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
class ItersProfiler(Profiler):
25
    def __init__(self, iter_text='iteration', **settings):
26
        Profiler.__init__(self, **settings)
27
        self.iter_text = iter_text
28
        self.iter_ct = None
29
    
30
    def add_iters(self, iter_ct):
31
        if self.iter_ct == None: self.iter_ct = 0
32
        self.iter_ct += iter_ct
33
    
34
    def stop(self, iter_ct=None):
35
        Profiler.stop(self)
36
        if iter_ct != None: self.add_iters(iter_ct)
37
    
38
    def msg(self):
39
        msg = Profiler.msg(self)
40
        if self.iter_ct != None and self.iter_ct > 0:
41
            msg += ('/'+format.int2str(self.iter_ct)+' '+self.iter_text+'(s) = '
42
            +format.to_si(float(dates.total_seconds(self.total))/self.iter_ct)
43
            +'s/'+self.iter_text)
44
        return msg
(32-32/50)