Skip to content

Commit d094387

Browse files
authored
Add monitoring decorator for performance tracking
This decorator monitors the execution time and memory usage of a function.
1 parent 93f8dd6 commit d094387

1 file changed

Lines changed: 36 additions & 0 deletions

File tree

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import time
2+
import tracemalloc
3+
4+
5+
def monitor(func):
6+
7+
def execute(*args, **kwargs):
8+
9+
tracemalloc.start()
10+
11+
initial_time = time.perf_counter()
12+
initial_memory = tracemalloc.get_traced_memory()[0]
13+
14+
tracemalloc.reset_peak()
15+
16+
try:
17+
output = func(*args, **kwargs)
18+
19+
finally:
20+
elapsed_time = time.perf_counter() - initial_time
21+
used_memory, max_memory = tracemalloc.get_traced_memory()
22+
23+
monitor.calls += 1
24+
monitor.duration += elapsed_time
25+
monitor.memory_usage += max_memory - initial_memory
26+
27+
tracemalloc.stop()
28+
29+
return output
30+
31+
return execute
32+
33+
34+
monitor.calls = 0
35+
monitor.duration = 0
36+
monitor.memory_usage = 0

0 commit comments

Comments
 (0)