From 4762ee99404d5d53a249ea2c19a42a623af185e6 Mon Sep 17 00:00:00 2001 From: firatadar <108763085+firatadar@users.noreply.github.com> Date: Mon, 6 Jan 2025 22:07:10 +0300 Subject: [PATCH] decorators_firat_adar_dal.py --- Week04/decorators_firat_adar_dal.py | 34 +++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Week04/decorators_firat_adar_dal.py diff --git a/Week04/decorators_firat_adar_dal.py b/Week04/decorators_firat_adar_dal.py new file mode 100644 index 00000000..a121f83c --- /dev/null +++ b/Week04/decorators_firat_adar_dal.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