Skip to content

Commit

Permalink
Merge ba9fd59 into 3f67b26
Browse files Browse the repository at this point in the history
  • Loading branch information
jsiirola committed Sep 5, 2019
2 parents 3f67b26 + ba9fd59 commit 2f55135
Showing 1 changed file with 40 additions and 18 deletions.
58 changes: 40 additions & 18 deletions pyutilib/misc/timing.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@

__all__ = ('TicTocTimer', 'tic', 'toc')

_loadTime = time.time()

class TicTocTimer(object):
"""A class to calculate and report elapsed time.
Expand All @@ -35,9 +33,11 @@ class TicTocTimer(object):
logging package. Note: timing logged using logger.info
"""
def __init__(self, ostream=None, logger=None):
self._lastTime = time.time()
self._lastTime = self._loadTime = time.time()
self._ostream = ostream
self._logger = logger
self._start_count = 0
self._cumul = 0

def tic(self, msg=None, ostream=None, logger=None):
"""Reset the tic/toc delta timer.
Expand Down Expand Up @@ -85,39 +85,61 @@ def toc(self, msg=None, delta=True, ostream=None, logger=None):
logging package (overrides the ostream provided when the
class was constructed). Note: timing logged using logger.info
"""

if msg is None:
msg = 'File "%s", line %s in %s' % \
traceback.extract_stack(limit=2)[0][:3]

now = time.time()
if delta:
if self._start_count or self._lastTime is None:
ans = self._cumul
if self._lastTime:
ans += time.time() - self._lastTime
if msg:
msg = "[%8.2f|%4d] %s\n" % (ans, self._start_count, msg)
elif delta:
ans = now - self._lastTime
self._lastTime = now
if msg:
msg = "[+%7.2f] %s\n" % (ans, msg)
else:
ans = now - _loadTime
ans = now - self._loadTime
if msg:
msg = "[%8.2f] %s\n" % (ans, msg)

if msg is None:
msg = 'File "%s", line %s in %s' % \
traceback.extract_stack(limit=2)[0][:3]
if msg:
if ostream is None:
ostream = self._ostream
if ostream is None and logger is None:
ostream = sys.stdout

if ostream is not None:
if delta:
ostream.write("[+%7.2f] %s\n" % (ans, msg))
else:
ostream.write("[%8.2f] %s\n" % (ans, msg))
ostream.write(msg)

if logger is None:
logger = self._logger

if logger is not None:
if delta:
logger.info("[+%7.2f] %s\n" % (ans, msg))
else:
logger.info("[%8.2f] %s\n" % (ans, msg))
logger.info(msg)

return ans

def stop(self):
try:
delta = time.time() - self._lastTime
except TypeError:
if self._lastTime is None:
raise RuntimeError(
"Stopping a TicTocTimer that was already stopped")
raise
self._cumul += delta
self._lastTime = None
return delta

def start(self):
if self._lastTime:
self.stop()
self._start_count += 1
self._lastTime = time.time()

_globalTimer = TicTocTimer()
tic = _globalTimer.tic
toc = _globalTimer.toc

0 comments on commit 2f55135

Please sign in to comment.