Skip to content

Commit 06e57f1

Browse files
authored
Add performance decorator for tracking metrics
Implement a performance decorator to track function metrics.
1 parent ec761d3 commit 06e57f1

1 file changed

Lines changed: 43 additions & 0 deletions

File tree

‎Week04/decorators_jalil_guliyev.py‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
2+
"""Week 04: Decorators homework."""
3+
4+
import functools
5+
import time
6+
import tracemalloc
7+
8+
9+
def performance(func):
10+
"""Track cumulative calls, elapsed time and peak memory allocation."""
11+
12+
@functools.wraps(func)
13+
def wrapper(*args, **kwargs):
14+
tracing_started_here = not tracemalloc.is_tracing()
15+
16+
if tracing_started_here:
17+
tracemalloc.start()
18+
19+
before_current, before_peak = tracemalloc.get_traced_memory()
20+
start = time.perf_counter()
21+
22+
try:
23+
return func(*args, **kwargs)
24+
25+
finally:
26+
elapsed = time.perf_counter() - start
27+
current, peak = tracemalloc.get_traced_memory()
28+
29+
allocated = max(0, peak - before_current)
30+
31+
performance.counter += 1
32+
performance.total_time += elapsed
33+
performance.total_mem += allocated
34+
35+
if tracing_started_here:
36+
tracemalloc.stop()
37+
38+
return wrapper
39+
40+
41+
performance.counter = 0
42+
performance.total_time = 0.0
43+
performance.total_mem = 0

0 commit comments

Comments
 (0)