From f7f9613ff0cc9ea373aae3a165bf10be29265a79 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20C=2E=20Riven=C3=A6s?= Date: Tue, 10 Sep 2024 14:56:38 +0200 Subject: [PATCH] FIX: _internals_ add a decorator function for timing (CPU demand) methods --- src/xtgeo/common/log.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/src/xtgeo/common/log.py b/src/xtgeo/common/log.py index c1743739f..3521b8de7 100644 --- a/src/xtgeo/common/log.py +++ b/src/xtgeo/common/log.py @@ -1,6 +1,8 @@ from __future__ import annotations import logging +import time +from functools import wraps def null_logger(name: str) -> logging.Logger: @@ -30,3 +32,30 @@ def null_logger(name: str) -> logging.Logger: logger = logging.getLogger(name) logger.addHandler(logging.NullHandler()) return logger + + +def functimer(func): + """A decorator function to measure the execution time of a function. + + Will emit a log message with the execution time in seconds, and is primarily + for developer use. + + Usage is simple, just add the decorator to the function you want to measure: + + @functimer + def my_function(): + pass + + """ + logger = null_logger(__name__) + + @wraps(func) + def wrapper(*args, **kwargs): + start_time = time.perf_counter() # Start the timer + result = func(*args, **kwargs) # Execute the function + end_time = time.perf_counter() # End the timer + elapsed_time = f"{end_time - start_time: .5f}" # Calculate the elapsed time + logger.debug("Function %s executed in %s seconds", func.__name__, elapsed_time) + return result + + return wrapper