Timer

class cocohelper.utils.timer.Timer[source]

Bases: ContextDecorator

Timer class that can be used both as a context manager and function/method decorator.

Usage:

>>> import math
>>> import time
>>>
>>> with Timer():
...    for i in range(42):
...        print("{}! = {:.5}...".format(i**2, str(math.factorial(i**2))))
>>>
>>> @Timer(end_msg="Second")
... def some_func():
...     time.sleep(1)
>>>
>>> with Timer(start_msg="Starting operation.", end_msg="Operation executed.") as t:
...    for i in range(42):
...        print("{}! = {:.5}...".format(i**2, str(math.factorial(i**2))))
>>>
>>> print(t.elapsed)

Instantiate new Timer.

Parameters:
  • start_msg – message to print before starting the operation.

  • end_msg – message (prefix) to print at the end of operation.

  • log_fn – logging function.

Method List

_recreate_cm()

Return a recreated instance of self.

Attributes List

elapsed

Methods Details

_recreate_cm()

Return a recreated instance of self.

Allows an otherwise one-shot context manager like _GeneratorContextManager to support use as a decorator via implicit recreation.

This is a private interface just for _GeneratorContextManager. See issue #11647 for details.

Attribute Details

elapsed