sloth.timers: Timing functions and classes

The sloth.timers module contains functions and classes for timing code.

class sloth.timers.StopWatch

Simple stopwatch for capturing code execution time.

start()

Starts the StopWatch.

stop()

Clears the stopwatch and returns the time elapsed since the start() method has been called. This method will return 0 if start has not been called.

Returns

The time - in seconds - elapsed since start() was called

Return type

float

lap()

Returns the time elapsed since the start() method was called without clearing the stopwatch. This method will return 0 if start has not been called.

Returns

The time - in seconds - elapsed since start() was called

Return type

int

Timer(seconds, func, args=None, kwargs=None):

Simple timer that executes a function after a timed interval

Parameters
  • seconds (int) – The number of seconds to call func after.

  • func (function) – The function to call after seconds seconds have elapsed.

  • args (list or tuple or None) – Positional arguments to pass to func.

  • kwargs (dict or None) – Keyword arguments to pass to func.

Raises

TypeError – if any of the arguments have incorrect types

sloth.timers.start()

Start the timer in the background. Eg:

>>> from sloth.timers import Timer
>>> from time import sleep
>>> def f():
...     print('Timer finished')
...
>>> def a():
...     t = Timer(5, f)
...     t.start()
...     print('Doing stuff')
...     sleep(3)
...     print('Doing more stuff')
...     sleep(4)
...     print('Finished doing stuff while the timer has executed in the background')
...
>>> a()
Doing stuff
Doing more stuff
Timer
Finished doing stuff while the timer has executed in the background
sloth.timers.stop()

Cancels the timer. If this method is called before start(), then the timer will not be run.

sloth.timers.join(timeout=None)

Wait until the timer finishes or timeout, if not None, has elapsed.

Parameters

timeout (int or float or None) – number of seconds to wait before returning. If None, then it returns when the timer has finished.

sloth.timers.run()

Run the timer in the main thread. This is the same as calling start() followed immediately by join()

sloth.timers.daemon

Warning

Please do not set this attribute unless you know what you are doing.

Controls whether or not the underlying thread that runs the timer is daemonic. This must be set before calling start(). This value defaults to True, meaning that the timer will be canceled if the program ends before completion.

Type

bool

Default

True