From 9b77cd3d1c9d4f4c70b5941b3d3dbdd754cf85ff Mon Sep 17 00:00:00 2001 From: Fatma Alsaghir Date: Sun, 1 Nov 2026 10:28:52 +0300 Subject: [PATCH] Implement function call counter and performance decorators Added two decorators: fn_w_counter for counting function calls and performance for measuring execution time and memory usage. --- Week04/decorators_fatma_alsaghir.py | 44 +++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Week04/decorators_fatma_alsaghir.py diff --git a/Week04/decorators_fatma_alsaghir.py b/Week04/decorators_fatma_alsaghir.py new file mode 100644 index 00000000..60767098 --- /dev/null +++ b/Week04/decorators_fatma_alsaghir.py @@ -0,0 +1,44 @@ +import time +import tracemalloc +from functools import wraps + + +def fn_w_counter(func): + @wraps(func) + def wrapper(*args, **kwargs): + wrapper.counter += 1 + + caller = func.__globals__.get("__name__", "__main__") + wrapper.callers[caller] = wrapper.callers.get(caller, 0) + 1 + + result = func(*args, **kwargs) + return result + + wrapper.counter = 0 + wrapper.callers = {} + return wrapper + + +def performance(func): + @wraps(func) + def wrapper(*args, **kwargs): + start_time = time.perf_counter() + + tracemalloc.start() + result = func(*args, **kwargs) + current_mem, peak_mem = tracemalloc.get_traced_memory() + tracemalloc.stop() + + elapsed_time = time.perf_counter() - start_time + + wrapper.counter += 1 + wrapper.total_time += elapsed_time + wrapper.total_mem += peak_mem + + return result + + wrapper.counter = 0 + wrapper.total_time = 0.0 + wrapper.total_mem = 0 + + return wrapper