From 660e64f70251203ef92b5f37a0b6c1e3bde766a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ya=C4=9Fmur?= Date: Sat, 2 Nov 2024 12:46:15 +0300 Subject: [PATCH] Create decorators_yagmur_tokdemir.py --- Week04/decorators_yagmur_tokdemir.py | 38 ++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Week04/decorators_yagmur_tokdemir.py diff --git a/Week04/decorators_yagmur_tokdemir.py b/Week04/decorators_yagmur_tokdemir.py new file mode 100644 index 00000000..b6f67b03 --- /dev/null +++ b/Week04/decorators_yagmur_tokdemir.py @@ -0,0 +1,38 @@ +import tracemalloc,time + + +def performance(f): + """ + This function is a decorator used to measure the performance of a function. + + Attributes: + counter (int): The number of times the decorated function has been called. + total_mem (int): The total peak memory usage across all calls to the decorated function. + total_time (float): The total time taken by all calls to the decorated function in seconds. + + Args: + f (function): The function to be decorated. + + Returns: + function: The wrapper function that performs the tracking and calls the original function. + + """ + + setattr(performance, 'counter', 0) + setattr(performance, 'total_mem', 0) + setattr(performance, 'total_time', 0) + + def wrapper(*args, **kwargs): + tracemalloc.start() + start_time = time.time() + result = f(*args, **kwargs) + end_time = time.time() + current, peak = tracemalloc.get_traced_memory() + tracemalloc.stop() + setattr(performance, 'counter', getattr(performance, 'counter') + 1) + setattr(performance, 'total_mem', getattr(performance, 'total_mem') + peak) + setattr(performance, 'total_time', getattr(performance, 'total_time') + end_time - start_time) + + return result + + return wrapper