delu.Timer#
- class delu.Timer[source]#
Measures time.
Measures time elapsed since the first call to
run
up to “now” plus shift. The shift accumulates all pauses time and can be manually changed with the methodsadd
andsub
. If a timer is just created/reset, the shift is 0.0.Note
Measurements are performed via
time.perf_counter
.Tutorial
import time assert Timer()() == 0.0 timer = Timer() timer.run() # start time.sleep(0.01) assert timer() # some time has passed timer.pause() elapsed = timer() time.sleep(0.01) assert timer() == elapsed # time didn't change because the timer is on pause timer.add(1.0) assert timer() == elapsed + 1.0 timer.run() # resume time.sleep(0.01) assert timer() > elapsed + 1.0 timer.reset() assert timer() == 0.0 with 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 = Timer() timer.add(3661) print('Time elapsed:', timer) assert str(timer) == f'{timer}' == '1:01:01' assert timer.format('%Hh %Mm %Ss') == '01h 01m 01s'
Time elapsed: 1:01:01
Timer
is pickle friendly:import pickle timer = 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.
Add non-negative delta to the shift.
Format the time elapsed since the start in a human-readable string.
Pause the timer.
Reset the timer.
Start/resume the timer.
Subtract non-negative delta from the shift.
Get time elapsed since the start.
Measure time within a context.
Leave the context and pause the timer.
- Return type