Source code for MDMC.common.time_keeper

"""
TimeKeeper class designed to track per-function level execution time.
"""

from collections import defaultdict
from time import time


[docs] class TimeKeeper: """ Class to track per-function execution time. A class designed for storing function timing information in class variable. The idea is to access the class variables throught a class instance, typically in a function decorator called `time_function_execution`. """ #: Number of times a function has been called. number_of_calls: dict[str, int] = defaultdict(int) #: Total accumulated time for given functions. execution_time: dict[str, float] = defaultdict(float) #: Time at which `TimeKeeper` started. started: float = time()
[docs] def function_called(self, fname: str): """ Increment number of the function calls for specified function. Parameters ---------- fname : str A descriptive name of the function that has been called. Typically this name will be generated by the :any:`time_function_execution` decorator. """ self.number_of_calls[fname] += 1
[docs] def time_passed(self, fname: str, exp_time: float): """ Compute accumulated execution time. Add the execution time of the function to the accumulated execution time from all the times that function has been called. Parameters ---------- fname : str A descriptive name of the function that has been called. Typically this name will be generated by the :any:`time_function_execution` decorator. exp_time : float The wall time that has expired during the function execution. """ self.execution_time[fname] += exp_time
[docs] def summarise_results(self) -> list[tuple[str, int, float]]: """ Convert all the recorded function timing data into a list. Returns ------- list[tuple[str, int, float]] Function name, number of function calls and accumulated execution time. """ results = [] for kk, nc in self.number_of_calls.items(): strk = str(kk) if strk in self.execution_time: results.append([strk, nc, self.execution_time[kk]]) return results
[docs] def total_time(self) -> float: """ Return the total wall time since we started timing. Returns ------- float Number of seconds since we started timing any of the functions. """ return time() - self.started