Create an Python decorator that measures the execution time of a function and logs it.…
- User
Create an Python decorator that measures the execution time of a function and logs it. Not applicable
Assistant
Problem: Create an Python decorator that measures the execution time of a function and logs it. Not applicable
Approach: it provides the highest available
Let me implement this solution.
The Solution
import time import logging from functools import wraps # 1. Configure logging to output to the console logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s' ) def execution_timer(func): """ A decorator that measures the execution time of a function and logs the result. """ @wraps(func) # Preserves the original function's metadata (name, docstring) def wrapper(*args, **kwargs): # 2. Record the start time start_time = time.perf_counter() try: # 3. Execute the actual function result = func(*args, **kwargs) return result finally: # 4. Record the end time and calculate duration end_time = time.perf_counter() duration = end_time - start_time # 5. Log the result # :.4f formats the float to 4 decimal places logging.info(f"Execution of '{func.__name__}' took {duration:.4f} seconds") return wrapper # --- Usage Examples --- @execution_timer def process_data(seconds): """Simulates a long-running process.""" print(f"Processing data for {seconds} seconds...") time.sleep(seconds) return "Data Processed" @execution_timer def quick_math(): return sum(range(1000000)) # Run the functions process_data(1.5) result = quick_math()