Source code for tcutility.timer

from time import perf_counter
import numpy as np
from tcutility import log
from types import FunctionType
import listfunc
import atexit
'''
Implements a decorator and context manager that records and stores the number of times a function
has been called and also the amount of time taken in total/per call
'''
times = {}
exec_start = perf_counter()

enabled: bool = True


[docs] class timer: ''' The main timer class. It acts both as a context-manager and decorator. ''' def __init__(self, name=None): if isinstance(name, FunctionType): self.function = name times.setdefault(name.__qualname__, {'calls': 0, 'timings': []}) else: self.name = name times.setdefault(self.name, {'calls': 0, 'timings': []}) def __enter__(self): self.start = perf_counter() return self def __exit__(self, *args, **kwargs): times[self.name]['calls'] += 1 times[self.name]['timings'].append(perf_counter() - self.start) def __call__(self, *args, **kwargs): times.setdefault(self.function.__qualname__, {'calls': 0, 'timings': []}) if enabled and __debug__: start = perf_counter() ret = self.function(*args, **kwargs) times[self.function.__qualname__]['calls'] += 1 times[self.function.__qualname__]['timings'].append(perf_counter() - start) return ret else: return self.function(*args, **kwargs)
# this makes sure that the timings are printed when Python quits running atexit.register(print_timings)