Skip to content

Commit 93ddaab

Browse files
authored
Add performance decorator for timing and memory tracking
This decorator tracks the execution time and memory usage of functions.
1 parent b536459 commit 93ddaab

1 file changed

Lines changed: 35 additions & 0 deletions

File tree

‎Week04/decorators_goktug_kayaci.py‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import time
2+
import tracemalloc
3+
4+
5+
def performance(fn):
6+
"""
7+
Measures the execution time and memory usage of a function.
8+
"""
9+
10+
def wrapper(*args, **kwargs):
11+
tracemalloc.start()
12+
start_time = time.perf_counter()
13+
14+
try:
15+
result = fn(*args, **kwargs)
16+
finally:
17+
elapsed_time = time.perf_counter() - start_time
18+
memory_used = tracemalloc.get_traced_memory()[1]
19+
tracemalloc.stop()
20+
21+
performance.counter += 1
22+
performance.total_time += elapsed_time
23+
performance.total_mem += memory_used
24+
25+
return result
26+
27+
wrapper.__name__ = fn.__name__
28+
wrapper.__doc__ = fn.__doc__
29+
30+
return wrapper
31+
32+
33+
performance.counter = 0
34+
performance.total_time = 0
35+
performance.total_mem = 0

0 commit comments

Comments
 (0)