Meaning
A decorator that measures and prints the execution time of a function.
Primary Function
Measures and prints the execution time of a wrapped function.
Communicative Purpose
Inform the developer about how long a function call took to execute.
Pattern
decorator
Core Structure
def timer(func):\n def wrapper(*args, **kwargs):\n import time\n start = time.perf_counter()\n result = func(*args, **kwargs)\n elapsed = time.perf_counter() - start\n print(f'{func.__name__} executed in {elapsed:.4f} sec')\n return result\n return wrapper
Função primária
Measures and prints the execution time of a wrapped function.
Propósito comunicativo
Inform the developer about how long a function call took to execute.
Situações de gatilho
When quick profiling or debugging of function runtime is needed.
Contextos
Used in debugging sessions, performance profiling, and educational examples of decorators.
Padrão
decorator
Estrutura central
def timer(func):\n def wrapper(*args, **kwargs):\n import time\n start = time.perf_counter()\n result = func(*args, **kwargs)\n elapsed = time.perf_counter() - start\n print(f'{func.__name__} executed in {elapsed:.4f} sec')\n return result\n return wrapper
Slots de substituição
func: callable to wrap; *args, **kwargs: arguments passed to the wrapped function.
Colocados típicos
- time.perf_counter
- functools.wraps
Substituições comuns
- logging.info instead of print
- time.process_time for CPU time
- returning elapsed time instead of printing.
Erros comuns
Forgetting to return the result; importing time inside the wrapper on each call; not preserving function metadata (__name__, __doc__).
Similar / contraste
context manager timer (using `with` statement); functools.lru_cache; timeit module.
Interferências
Printing inside the wrapper can affect timing accuracy; for precise measurements prefer logging or the timeit module.
Família do chunk
- py-decorator
- py-context-manager
- py-functools-wraps
- py-logging-decorator
Nuance
Measures wall‑clock time; output goes to stdout; not suitable for production profiling without modification.
Efeito pragmático
Provides immediate feedback on function runtime, useful for quick debugging and learning.
Dica de memória
Think of a stopwatch wrapping a function call.
Upgrade path
functools.wraps wrapper to preserve function metadata and docstring
Log in to save chunks.