Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions Week05/decorators_omer_gezici.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import time
import tracemalloc
from functools import wraps

def performance(func):
"""
A decorator that measures the performance of a function and stores statistics.

This decorator tracks the number of times the function is called, the total
execution time, and the peak memory consumption. These metrics are stored
as attributes on the wrapper function itself.

:param func: The function to be decorated and measured.
:type func: callable
:return: The wrapper function that executes the original function and records metrics.
:rtype: callable
"""
@wraps(func)
def wrapper(*args, **kwargs):

wrapper.counter += 1

tracemalloc.start()
start_time = time.perf_counter()

result = func(*args, **kwargs)

end_time = time.perf_counter()
current_mem, peak_mem = tracemalloc.get_traced_memory()
tracemalloc.stop()

wrapper.total_time += (end_time - start_time)
wrapper.total_mem += peak_mem

return result

wrapper.counter = 0
wrapper.total_time = 0.0
wrapper.total_mem = 0

return wrapper