From d9c2cb67adb12e7a247a4d8226beffb9ec46c11b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Turhan=20G=C3=BCnd=C3=BCzo=C4=9Flu?= <220315031@ogr.cbu.edu.tr> Date: Tue, 7 Apr 2026 18:34:09 +0300 Subject: [PATCH] Add performance tracking decorator This decorator tracks the performance of a function by measuring its execution time and memory usage. --- Week04/decorators_turhan_gunduzoglu.py | 34 ++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Week04/decorators_turhan_gunduzoglu.py diff --git a/Week04/decorators_turhan_gunduzoglu.py b/Week04/decorators_turhan_gunduzoglu.py new file mode 100644 index 00000000..a121f83c --- /dev/null +++ b/Week04/decorators_turhan_gunduzoglu.py @@ -0,0 +1,34 @@ +import time +import tracemalloc + +def performance(fn): + """A decorator to measure the performance (time and memory usage) of a function.""" + # Static variables for performance tracking + if not hasattr(performance, "counter"): + performance.counter = 0 + performance.total_time = 0 + performance.total_mem = 0 + + def wrapper(*args, **kwargs): + # Increment the call counter + performance.counter += 1 + + # Start tracking memory and time + tracemalloc.start() + start_time = time.time() + + # Execute the decorated function + result = fn(*args, **kwargs) + + # Stop tracking memory and calculate elapsed time + end_time = time.time() + current, peak = tracemalloc.get_traced_memory() + tracemalloc.stop() + + # Update total memory and time + performance.total_mem += peak + performance.total_time += (end_time - start_time) + + return result + + return wrapper