From 64c6ae96676a8d831ac5979d3e6c46892f7b546e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mehmet=20Balc=C4=B1?= <148548201+MehmetxBalci@users.noreply.github.com> Date: Thu, 2 Apr 2026 16:11:19 +0300 Subject: [PATCH] Add performance tracking decorator This decorator tracks the performance of a function by measuring execution time and memory usage. --- Week04/decorators_mehmet_balci.py | 37 +++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Week04/decorators_mehmet_balci.py diff --git a/Week04/decorators_mehmet_balci.py b/Week04/decorators_mehmet_balci.py new file mode 100644 index 00000000..62fbd19d --- /dev/null +++ b/Week04/decorators_mehmet_balci.py @@ -0,0 +1,37 @@ +import time +import tracemalloc + +def performance(func): + # Initialize static variables only once (if they don't exist) + if not hasattr(performance, "counter"): + performance.counter = 0 # Number of times the function is called + performance.total_time = 0.0 # Total execution time + performance.total_mem = 0 # Total peak memory usage + + def wrapper(*args, **kwargs): + # Start high-resolution timer + start = time.perf_counter() + + # Start tracking memory allocations + tracemalloc.start() + + try: + # Execute the original function + return func(*args, **kwargs) + finally: + # Calculate elapsed time + elapsed = time.perf_counter() - start + + # Get memory usage (peak = maximum memory used) + _, peak = tracemalloc.get_traced_memory() + + # Stop memory tracking + tracemalloc.stop() + + # Update statistics + performance.counter += 1 + performance.total_time += elapsed + performance.total_mem += peak + + # Return the wrapper function instead of the original + return wrapper