Skip to content

Commit df3f3dd

Browse files
authored
Merge pull request #512 from katex35/patch-4
Create decorators_gokay_sahin.py
2 parents d3f6594 + dbf9da0 commit df3f3dd

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Week04/decorators_gokay_sahin.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import time
2+
import tracemalloc
3+
4+
def performance(fn):
5+
"""
6+
Decorator to measure performance of a function, including
7+
execution time and memory usage.
8+
9+
This decorator tracks:
10+
- The number of times the function is called.
11+
- The cumulative time taken by the function.
12+
- The cumulative peak memory usage.
13+
14+
:param fn: The function to be wrapped and measured.
15+
:return: The result of the wrapped function.
16+
"""
17+
if not hasattr(performance, 'counter'):
18+
performance.counter = 0
19+
performance.total_time = 0
20+
performance.total_mem = 0
21+
22+
def wrapper(*args, **kwargs):
23+
tracemalloc.start()
24+
25+
time_before = time.time()
26+
27+
result = fn(*args, **kwargs)
28+
29+
time_after = time.time()
30+
31+
curr_mem, peak_mem = tracemalloc.get_traced_memory()
32+
tracemalloc.stop()
33+
34+
performance.counter += 1
35+
performance.total_time += (time_after - time_before)
36+
performance.total_mem += peak_mem
37+
38+
return result
39+
40+
return wrapper

0 commit comments

Comments
 (0)