1. import time
  2. import functools
  3. import logging
  4. logging.basicConfig(level=logging.INFO)
  5. def time_it(func):
  6. """Decorator to measure execution time of a function."""
  7. @functools.wraps(func)
  8. def wrapper(*args, **kwargs):
  9. start_time = time.time()
  10. result = func(*args, **kwargs)
  11. end_time = time.time()
  12. execution_time = end_time - start_time
  13. logging.info(f"Function '{func.__name__}' took {execution_time:.4f} seconds")
  14. return result
  15. return wrapper
  16. if __name__ == '__main__':
  17. @time_it
  18. def my_task(n):
  19. """A short-lived task."""
  20. time.sleep(0.1) # Simulate some work
  21. return n * 2
  22. result = my_task(5)
  23. print(f"Result: {result}")
  24. @time_it
  25. def another_task(text):
  26. """Another short task"""
  27. time.sleep(0.05)
  28. return text.upper()
  29. print(another_task("hello"))

Add your comment