Skip to content

Commit c6b8b76

Browse files
authored
Create decorators_heval_sogut.py
1 parent 5ae1705 commit c6b8b76

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

Week04/decorators_heval_sogut.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import time
2+
import tracemalloc
3+
4+
def performance(func):
5+
6+
# This is the wrapper function.
7+
def wrapper(*args, **kwargs):
8+
"""Wrapper function that adds performance tracking."""
9+
10+
# --- "Before" logic ---
11+
tracemalloc.start()
12+
start_time = time.perf_counter()
13+
14+
# Execute the original function
15+
result = func(*args, **kwargs)
16+
17+
# --- "After" logic ---
18+
# Get performance metrics
19+
end_time = time.perf_counter()
20+
_current_mem, peak_mem = tracemalloc.get_traced_memory()
21+
tracemalloc.stop()
22+
23+
elapsed_time = end_time - start_time
24+
25+
# Update the statistics
26+
performance.counter += 1
27+
performance.total_time += elapsed_time
28+
performance.total_mem += peak_mem
29+
30+
return result
31+
32+
# The decorator returns the new wrapper function
33+
return wrapper
34+
35+
# Initialize the state as attributes of the function object.
36+
# This state will be shared across all uses of the @performance decorator.
37+
performance.counter = 0
38+
performance.total_time = 0.0
39+
performance.total_mem = 0

0 commit comments

Comments
 (0)