Skip to content

Commit fa03471

Browse files
authored
Merge pull request #692 from berriesyl/patch-6
Create decorators_berra_soyler.py
2 parents 024949b + b48995a commit fa03471

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

Week04/decorators_berra_soyler.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import time
2+
import tracemalloc
3+
4+
def performance(func):
5+
"""
6+
A decorator that measures the performance of a function by tracking the
7+
number of calls, total execution time, and peak memory usage.
8+
9+
Attributes:
10+
- counter: Tracks the number of times the decorated function is called.
11+
- total_time: Accumulates the total execution time across all calls.
12+
- total_mem: Accumulates the peak memory usage across all calls.
13+
"""
14+
setattr(performance, 'counter', 0)
15+
setattr(performance, 'total_time', 0.0)
16+
setattr(performance, 'total_mem', 0.0)
17+
18+
def inner(*args, **kwargs):
19+
tracemalloc.start()
20+
start_time = time.time()
21+
result = func(*args, **kwargs)
22+
end_time = time.time()
23+
current, peak = tracemalloc.get_traced_memory()
24+
tracemalloc.stop()
25+
26+
setattr(performance, 'counter', getattr(performance, 'counter') + 1)
27+
setattr(performance, 'total_time', getattr(performance, 'total_time') + (end_time - start_time))
28+
setattr(performance, 'total_mem', getattr(performance, 'total_mem') + peak)
29+
30+
return result
31+
32+
return inner

0 commit comments

Comments
 (0)