diff --git a/Week05/decorators_omer_gezici.py b/Week05/decorators_omer_gezici.py new file mode 100644 index 00000000..a39cbe02 --- /dev/null +++ b/Week05/decorators_omer_gezici.py @@ -0,0 +1,41 @@ +import time +import tracemalloc +from functools import wraps + +def performance(func): + """ + A decorator that measures the performance of a function and stores statistics. + + This decorator tracks the number of times the function is called, the total + execution time, and the peak memory consumption. These metrics are stored + as attributes on the wrapper function itself. + + :param func: The function to be decorated and measured. + :type func: callable + :return: The wrapper function that executes the original function and records metrics. + :rtype: callable + """ + @wraps(func) + def wrapper(*args, **kwargs): + + wrapper.counter += 1 + + tracemalloc.start() + start_time = time.perf_counter() + + result = func(*args, **kwargs) + + end_time = time.perf_counter() + current_mem, peak_mem = tracemalloc.get_traced_memory() + tracemalloc.stop() + + wrapper.total_time += (end_time - start_time) + wrapper.total_mem += peak_mem + + return result + + wrapper.counter = 0 + wrapper.total_time = 0.0 + wrapper.total_mem = 0 + + return wrapper