Skip to content

Commit

Permalink
FIX: _internals_ add a decorator function for timing (CPU demand) met…
Browse files Browse the repository at this point in the history
…hods
  • Loading branch information
jcrivenaes committed Sep 12, 2024
1 parent 4c2e11c commit f7f9613
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/xtgeo/common/log.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from __future__ import annotations

import logging
import time
from functools import wraps


def null_logger(name: str) -> logging.Logger:
Expand Down Expand Up @@ -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

0 comments on commit f7f9613

Please sign in to comment.