From fe485d7121340e681c651a71a7968843b7740efc Mon Sep 17 00:00:00 2001 From: ayseearslan09-byte Date: Mon, 2 Nov 2026 20:29:20 +0300 Subject: [PATCH] Add performance decorator to track function metrics This decorator tracks the performance of functions by measuring execution time and memory usage. --- Week04/decorators_ayse_arslan.py | 47 ++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Week04/decorators_ayse_arslan.py diff --git a/Week04/decorators_ayse_arslan.py b/Week04/decorators_ayse_arslan.py new file mode 100644 index 00000000..914bf6a9 --- /dev/null +++ b/Week04/decorators_ayse_arslan.py @@ -0,0 +1,47 @@ +import time +import tracemalloc +from functools import wraps + + +def performance(func): + @wraps(func) + def wrapper(*args, **kwargs): + + if not tracemalloc.is_tracing(): + tracemalloc.start() + + tracemalloc.reset_peak() + before = tracemalloc.get_traced_memory()[0] + + start_time = time.perf_counter() + + result = func(*args, **kwargs) + + end_time = time.perf_counter() + + current, peak = tracemalloc.get_traced_memory() + + wrapper.counter += 1 + wrapper.total_time += end_time - start_time + wrapper.total_mem += max(0, peak - before) + + return result + + wrapper.counter = 0 + wrapper.total_time = 0.0 + wrapper.total_mem = 0 + + return wrapper + + +# Example function +@performance +def calculate(): + numbers = [i for i in range(1000)] + return sum(numbers) + + +print(calculate()) +print("Counter:", calculate.counter) +print("Total time:", calculate.total_time) +print("Total memory:", calculate.total_mem)