StopUhr#

class stopuhr.StopUhr(printer: callable = <built-in function print>)[source]#

Bases: object

Very high level benchmarking contextmanager.

Example

Use a stateful timer to measure the time taken in a loop. This also supports the printer and res arguments. The log argument of each call can be used to suppress the output.

>>> from stopuhr import StopUhr

>>> stopuhr = StopUhr()

>>> for i in range(5):
>>>     with stopuhr("Sleeping", log=False):
>>>         time.sleep(0.2)

>>> # Print a summary with the mean and standard deviation of the durations.
>>> stopuhr.summary()
Sleeping took 0.20 ± 0.00 s (n=5 -> total=1.00s)

The reset` command resets the state of the timer, note that this function is happening in-place.

>>> stopuhr.reset()

The previous behavior can be achieved with the start and stop methods. Here, the stop method also supports the log and res arguments.

>>> for i in range(5):
>>>     stopuhr.start("Sleeping")
>>>     time.sleep(0.2)
>>>     stopuhr.stop("Sleeping", log=False)

>>> stopuhr.summary()
Sleeping took 0.20 ± 0.00 s (n=5 -> total=1.00s)

The stateful timer can also measure multiple durations at once.

>>> stopuhr.reset()

>>> # Single duration
>>> with stopuhr("A (single 0.2s sleep)", log=False):
>>>     time.sleep(0.2)

>>> for i in range(5):
>>>     with stopuhr("B (multiple 0.2s sleeps)", log=False):
>>>         time.sleep(0.2)
>>>     with stopuhr("C (multiple 0.1s sleeps)", log=False):
>>>         time.sleep(0.1)

>>> stopuhr.summary()
A (single 0.2s sleep) took 0.20 s
B (multiple 0.2s sleeps) took 0.20 ± 0.00 s (n=5 -> total=1.00s)
C (multiple 0.1s sleeps) took 0.10 ± 0.00 s (n=5 -> total=0.50s)
export() pd.DataFrame[source]#

Export the durations as a pandas DataFrame.

Returns:

A pandas DataFrame with the durations.

Return type:

pd.DataFrame

reset()[source]#

Reset the durations.

start(msg: str)[source]#

Start the timer for a msg.

Parameters:

msg (str) – The msg / key to store the start time under.

stop(key: str, res: int = 2, log: bool = True)[source]#

Stop the timer for a key.

Parameters:
  • key (str) – The key to store the duration under.

  • res (int, optional) – The number of decimal places to round to. Defaults to 2.

  • log (bool, optional) – Whether to log the duration. Defaults to True.

summary(res: int = 2)[source]#

Print a summary of the durations.

Parameters:

res (int, optional) – The number of decimal places to round to. Defaults to 2.