Skip to content

Instantly share code, notes, and snippets.

@bgbg
Created January 6, 2016 08:40
Show Gist options
  • Save bgbg/61451bc9332659be32ca to your computer and use it in GitHub Desktop.
Save bgbg/61451bc9332659be32ca to your computer and use it in GitHub Desktop.
A simple stopwatch object that mimics Matlab's tic - toc pair
import time
class TicToc:
""" A simple stopwatch object"""
def __init__(self, name=None, start=True):
if name is None:
name = 'Running time'
self.name = name
self.dt = 0.0
self._t_start = None
self.state = 'off'
if start is True:
self.start()
def tic(self):
""" Start and return self"""
self._t_start = time.time()
self.dt = 0
self.state = 'on'
return self
def start(self):
return self.tic()
def toc(self):
""" Stop and return self's string representation """
self.stop()
return self.__str__()
def stop(self):
assert self.state == 'on'
t_stop = time.time()
self.state = 'off'
dt = t_stop - self._t_start
self.dt += dt
self._t_start = None
return self
def restart(self):
if self.is_running():
self.stop()
return self.tic()
def running_time(self):
if self.state == 'on':
t_curr = time.time()
dt = t_curr - self._t_start
dt += self.dt
else:
dt = self.dt
return dt
def is_running(self):
return self.state == 'on'
def __str__(self):
SECONDS_PER_MINUTE = 60.
SECONDS_PER_HOUR = 60. * SECONDS_PER_MINUTE
dt = self.running_time()
int_hours = int(dt / SECONDS_PER_HOUR)
minutes = (dt - int_hours * SECONDS_PER_HOUR) / SECONDS_PER_MINUTE
int_minutes = int(minutes)
seconds = dt - int_hours * SECONDS_PER_HOUR - int_minutes * SECONDS_PER_MINUTE
if int_hours > 0:
ret = '%02d:%02d:%04.1f' % (int_hours, int_minutes, seconds)
else:
ret = '%02d:%04.1f' % (int_minutes, seconds)
if bool(self.name):
ret = '%s: %s' % (self.name, ret)
return ret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment