Skip to content

Commit 7e6f963

Browse files
authored
Merge pull request #845 from firatadar/patch-5
decorators_firat_adar_dal.py
2 parents a3a603c + 4762ee9 commit 7e6f963

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

Week04/decorators_firat_adar_dal.py

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import time
2+
import tracemalloc
3+
4+
def performance(fn):
5+
"""A decorator to measure the performance (time and memory usage) of a function."""
6+
# Static variables for performance tracking
7+
if not hasattr(performance, "counter"):
8+
performance.counter = 0
9+
performance.total_time = 0
10+
performance.total_mem = 0
11+
12+
def wrapper(*args, **kwargs):
13+
# Increment the call counter
14+
performance.counter += 1
15+
16+
# Start tracking memory and time
17+
tracemalloc.start()
18+
start_time = time.time()
19+
20+
# Execute the decorated function
21+
result = fn(*args, **kwargs)
22+
23+
# Stop tracking memory and calculate elapsed time
24+
end_time = time.time()
25+
current, peak = tracemalloc.get_traced_memory()
26+
tracemalloc.stop()
27+
28+
# Update total memory and time
29+
performance.total_mem += peak
30+
performance.total_time += (end_time - start_time)
31+
32+
return result
33+
34+
return wrapper

0 commit comments

Comments
 (0)