Skip to content

Commit d7932c3

Browse files
authored
Implement performance decorator for function metrics
This decorator tracks the performance of a function, measuring execution time and memory usage.
1 parent 71f5b39 commit d7932c3

1 file changed

Lines changed: 32 additions & 0 deletions

File tree

Week04/decorators_alp_ozdemir.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import functools
2+
import time
3+
import tracemalloc
4+
5+
def performance(func):
6+
@functools.wraps(func)
7+
def wrapper(*args, **kwargs):
8+
9+
tracemalloc.start()
10+
start_time = time.perf_counter()
11+
12+
try:
13+
14+
result = func(*args, **kwargs)
15+
finally:
16+
17+
current, peak = tracemalloc.get_traced_memory()
18+
tracemalloc.stop()
19+
end_time = time.perf_counter()
20+
21+
22+
performance.counter += 1
23+
performance.total_time += (end_time - start_time)
24+
performance.total_mem += peak
25+
26+
return result
27+
return wrapper
28+
29+
30+
performance.counter = 0
31+
performance.total_time = 0
32+
performance.total_mem = 0

0 commit comments

Comments
 (0)