Coverage for /Users/Newville/Codes/xraylarch/larch/utils/debugtime.py: 25%
44 statements
« prev ^ index » next coverage.py v7.3.2, created at 2023-11-09 10:08 -0600
« prev ^ index » next coverage.py v7.3.2, created at 2023-11-09 10:08 -0600
1#!/usr/bin/env python
3import time
4import sys
6class debugtime(object):
7 def __init__(self, verbose=False, _larch=None):
8 self._larch = _larch
9 self.clear()
10 self.verbose = verbose
11 self.add('init')
13 def clear(self):
14 self.times = []
16 def _print(self, *args):
17 writer = sys.stdout
18 if self._larch is not None:
19 writer = self._larch.writer
20 writer.write(*args)
23 def add(self,msg=''):
24 if self.verbose:
25 self._print(msg, time.ctime())
26 self.times.append((msg, time.time()))
28 def get_report(self):
29 m0, t0 = self.times[0]
30 tlast= t0
31 out = []
32 add = out.append
33 add("# %s %s " % (m0,time.ctime(t0)))
34 add("#----------------")
35 add("# Message Total Delta")
36 for m,t in self.times[1:]:
37 tt = t-t0
38 dt = t-tlast
39 if len(m)<32:
40 m = m + ' '*(32-len(m))
41 add(" %32s %.3f %.3f" % (m,tt, dt))
42 tlast = t
43 add('')
44 return "\n".join(out)
46 def show(self):
47 self._print(self.get_report())
49 def save(self, fname='debugtimer.dat'):
50 dat = self.get_report()
51 with open(fname, 'w') as fh:
52 fh.write('%s\n' % dat)
54def debugtimer(_larch=None):
55 """debugtimer returns a Timer object that can be used
56 to time the running of portions of code, and then
57 write a simple report of the results. the Timer object
58 has methods:
60 clear() -- reset Timer
61 add(msg) -- record time, with message
62 show_report -- print timer report
64 An example:
66 timer = debugtimer()
67 x = 1
68 timer.add('now run foo')
69 foo()
70 timer.add('now run bar')
71 bar()
72 timer.show_report()
73 """
74 return debugtime(_larch=_larch)