I recently wanted to find out which functions take which amount of time in a project, and calling a timer and printing the difference inside a function that is called multiple times does not scale well.
That's why I created my own little decorator function:
from timeit import default_timer as timer time_in = dict() def measure(func): def saveTime(identifier, time): global time_in if identifier not in time_in: time_in[identifier] = 0 time_in[identifier] += time def measure_wrapper(*args, **kwargs): global time_in start = timer() value = func(*args, **kwargs) saveTime(func.__name__, timer() - start) return value return measure_wrapper
It works by prepending every function (or method) that should be measured with
@measure and then printing the dict at the end of the main function. It works as intended. However, it adds a global variable and I'm sure there must already be a solution like it, I just haven't found it.
So, my questions are:
- Is it possible to remove the global variable?
- Is there already a solution like this in the standard libs?