From b48995a28dcb971545988b1a2cd5c03689062acf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berra=20S=C3=96YLER?= <118564672+berriesyl@users.noreply.github.com> Date: Sat, 2 Nov 2024 13:17:05 +0300 Subject: [PATCH] Create decorators_berra_soyler.py --- Week04/decorators_berra_soyler.py | 32 +++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Week04/decorators_berra_soyler.py diff --git a/Week04/decorators_berra_soyler.py b/Week04/decorators_berra_soyler.py new file mode 100644 index 00000000..684ab2a9 --- /dev/null +++ b/Week04/decorators_berra_soyler.py @@ -0,0 +1,32 @@ +import time +import tracemalloc + +def performance(func): + """ + A decorator that measures the performance of a function by tracking the + number of calls, total execution time, and peak memory usage. + + Attributes: + - counter: Tracks the number of times the decorated function is called. + - total_time: Accumulates the total execution time across all calls. + - total_mem: Accumulates the peak memory usage across all calls. + """ + setattr(performance, 'counter', 0) + setattr(performance, 'total_time', 0.0) + setattr(performance, 'total_mem', 0.0) + + def inner(*args, **kwargs): + tracemalloc.start() + start_time = time.time() + result = func(*args, **kwargs) + end_time = time.time() + current, peak = tracemalloc.get_traced_memory() + tracemalloc.stop() + + setattr(performance, 'counter', getattr(performance, 'counter') + 1) + setattr(performance, 'total_time', getattr(performance, 'total_time') + (end_time - start_time)) + setattr(performance, 'total_mem', getattr(performance, 'total_mem') + peak) + + return result + + return inner