Skip to content

Commit fe485d7

Browse files
Add performance decorator to track function metrics
This decorator tracks the performance of functions by measuring execution time and memory usage.
1 parent 9a399e7 commit fe485d7

1 file changed

Lines changed: 47 additions & 0 deletions

File tree

‎Week04/decorators_ayse_arslan.py‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import time
2+
import tracemalloc
3+
from functools import wraps
4+
5+
6+
def performance(func):
7+
@wraps(func)
8+
def wrapper(*args, **kwargs):
9+
10+
if not tracemalloc.is_tracing():
11+
tracemalloc.start()
12+
13+
tracemalloc.reset_peak()
14+
before = tracemalloc.get_traced_memory()[0]
15+
16+
start_time = time.perf_counter()
17+
18+
result = func(*args, **kwargs)
19+
20+
end_time = time.perf_counter()
21+
22+
current, peak = tracemalloc.get_traced_memory()
23+
24+
wrapper.counter += 1
25+
wrapper.total_time += end_time - start_time
26+
wrapper.total_mem += max(0, peak - before)
27+
28+
return result
29+
30+
wrapper.counter = 0
31+
wrapper.total_time = 0.0
32+
wrapper.total_mem = 0
33+
34+
return wrapper
35+
36+
37+
# Example function
38+
@performance
39+
def calculate():
40+
numbers = [i for i in range(1000)]
41+
return sum(numbers)
42+
43+
44+
print(calculate())
45+
print("Counter:", calculate.counter)
46+
print("Total time:", calculate.total_time)
47+
print("Total memory:", calculate.total_mem)

0 commit comments

Comments
 (0)