delu.Timer#
- class delu.Timer[source]#
Measures time.
A simple timer with the following features:
can measure time :)
can be safely pickled and unpickled (i.e. can be a part of a checkpoint)
can be paused/resumed
can be prettyprinted or formatted with a custom format string
can be a context manager
Note
Technically, the timer measures the time elapsed since the first call to
Timer.run
up to “now” minus pauses. Measurements are performed viatime.perf_counter
.Tutorial
import time timer = delu.Timer() timer.run() # run the timer time.sleep(0.01) assert timer() > 0.0 # get the elapsed time # measure time between two events start = timer() time.sleep(0.01) end = timer() duration = end - start timer.pause() elapsed = timer() time.sleep(0.01) assert timer() == elapsed # time didn't change because the timer is on pause timer.run() # resume time.sleep(0.01) assert timer() > elapsed timer.reset() assert timer() == 0.0 with delu.Timer() as timer: time.sleep(0.01) # timer is on pause and timer() returns the time elapsed within the context
Timer
can be printed and formatted in a human-readable manner:timer = delu.Timer() timer.run() <let's assume that exactly 3661.0 seconds have passed> print('Time elapsed:', timer) # prints "Time elapsed: 1:01:01" assert str(timer) == f'{timer}' == '1:01:01' assert timer.format('%Hh %Mm %Ss') == '01h 01m 01s'
Timer
is pickle friendly:import pickle timer = delu.Timer() timer.run() time.sleep(0.01) timer.pause() old_value = timer() timer_bytes = pickle.dumps(timer) time.sleep(0.01) new_timer = pickle.loads(timer_bytes) assert new_timer() == old_value
Methods
Initialize self.
Format the time elapsed since the start in a human-readable string.
Pause the timer.
Reset the timer.
Start/resume the timer.
Get the time elapsed since the start.
Measure time within a context.
Leave the context and pause the timer.