Module stop_watch.

StopWatch

The StopWatch class can be used during testing to start a clock, pause for a certain amount of time relative to the started clock, and then stop the clock and get the elapsed time.

Example:

verify timing of event

>>> import threading
>>> import time
>>> from scottbrian_utils.stop_watch import StopWatch
>>> def main() -> None:
...     def f1():
...         print('f1 entered')
...         stop_watch.start_clock(clock_iter=1)
...         print('f1 about to wait')
...         f1_event.wait()
...         print('f1 back from wait')
...         assert 2.5 <= stop_watch.duration() <= 2.6
...         print('f1 exiting')
...     print('mainline entered')
...     stop_watch = StopWatch()
...     f1_thread = threading.Thread(target=f1)
...     f1_event = threading.Event()
...     print('mainline about to start f1')
...     f1_thread.start()
...     stop_watch.pause(2.5, clock_iter=1)
...     print('mainline about to set f1_event')
...     f1_event.set()
...     f1_thread.join()
...     print('mainline exiting')
>>> main()
mainline entered
mainline about to start f1
f1 entered
f1 about to wait
mainline about to set f1_event
f1 back from wait
f1 exiting
mainline exiting

The stop_watch module contains:

  1. StopWatch class with methods:

    1. duration

    2. pause

    3. start_clock

class stop_watch.StopWatch

StopWatch class for testing.

The StopWatch class is used to assist in the testing of multi-threaded functions. It provides a set of methods that help with verification of timed event. The test case setup involves a mainline thread that starts one or more remote threads. The start_clock and duration methods are used to verify event times.

Initialize the object.

duration()

Return the number of seconds from the start_time.

Return type:

float

Returns:

number of seconds from the start_time

pause(seconds, clock_iter)

Sleep for the number of input seconds relative to start_time.

Parameters:
  • seconds (Union[int, float]) – number of seconds to pause from the start_time for the given clock_iter.

  • clock_iter (int) – clock clock_iter to pause on

Return type:

None

Notes

  1. The clock_iter is used to identify the clock that is currently in use. A remote thread wants to pause for a given number of seconds relative to the StopWatch start_time for a given iteration of the clock. We will do a sleep loop until the given clock_iter matches the StopWatch clock_iter.

start_clock(clock_iter)

Set the start_time to the current time.

Parameters:

clock_iter (int) – clock_iter to set for the clock

Return type:

None