1
|
# Profiling: Times operations and provides the user with statistical information
|
2
|
|
3
|
import sys
|
4
|
import datetime
|
5
|
|
6
|
import format
|
7
|
|
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
|
msg += ('/'+format.int2str(self.iter_ct)+' '+self.iter_text+'(s) = '
|
41
|
+format.to_si(float(self.total.total_seconds())/self.iter_ct)
|
42
|
+'s/'+self.iter_text)
|
43
|
return msg
|