Skip to content

Latest commit

 

History

History
33 lines (27 loc) · 749 Bytes

20221026124022.md

File metadata and controls

33 lines (27 loc) · 749 Bytes

timeit decorator

A timer decorator measuring the start and end timings of a function's execution, printing the duration.

As per best practice I use @wraps to preserve the function's metadata (e.g. docstring).

>>> from functools import wraps
>>> from time import time, sleep

>>> def timing(f):
...     """A simple timer decorator"""
...     @wraps(f)
...     def wrapper(*args, **kwargs):
...         start = time()
...         result = f(*args, **kwargs)
...         end = time()
...         print(f'Elapsed time {f.__name__}: {end - start}')
...         return result
...     return wrapper
...

>>> @timing
... def func():
...     sleep(2)
...     print('Done')
...
>>> func()
Done
Elapsed time func: 2.0039281845092773

#decorators