Skip to content

Commit 85c7cbf

Browse files
authored
Add performance decorator for function profiling
1 parent b60efee commit 85c7cbf

1 file changed

Lines changed: 41 additions & 0 deletions

File tree

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import time
2+
import tracemalloc
3+
from functools import wraps
4+
5+
def performance(func):
6+
call_count = 0
7+
total_time = 0.0
8+
total_mem = 0
9+
10+
@wraps(func)
11+
def wrapper(*args, **kwargs):
12+
nonlocal call_count, total_time, total_mem
13+
14+
tracing_started = tracemalloc.is_tracing()
15+
16+
if not tracing_started:
17+
tracemalloc.start()
18+
19+
tracemalloc.reset_peak()
20+
start_time = time.perf_counter()
21+
22+
try:
23+
result = func(*args, **kwargs)
24+
return result
25+
26+
finally:
27+
end_time = time.perf_counter()
28+
current_mem, peak_mem = tracemalloc.get_traced_memory()
29+
30+
call_count += 1
31+
total_time += end_time - start_time
32+
total_mem += peak_mem
33+
34+
if not tracing_started:
35+
tracemalloc.stop()
36+
37+
wrapper.call_count = lambda: call_count
38+
wrapper.total_time = lambda: total_time
39+
wrapper.total_mem = lambda: total_mem
40+
41+
return wrapper

0 commit comments

Comments
 (0)