Skip to content

Commit a481448

Browse files
Add performance decorator for function statistics
Introduced a performance decorator to collect function execution statistics including time and memory usage.
1 parent 5f77f8c commit a481448

1 file changed

Lines changed: 31 additions & 0 deletions

File tree

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import time
2+
import tracemalloc
3+
import functools
4+
5+
6+
class performance:
7+
"""Decorator class collecting performance statistics of functions."""
8+
counter = 0
9+
total_time = 0.0
10+
total_mem = 0
11+
12+
def __init__(self, func):
13+
functools.update_wrapper(self, func)
14+
self.func = func
15+
16+
def __call__(self, *args, **kwargs):
17+
was_tracing = tracemalloc.is_tracing()
18+
if not was_tracing:
19+
tracemalloc.start()
20+
mem_before = tracemalloc.get_traced_memory()[0]
21+
t0 = time.perf_counter()
22+
try:
23+
return self.func(*args, **kwargs)
24+
finally:
25+
t1 = time.perf_counter()
26+
mem_after, peak = tracemalloc.get_traced_memory()
27+
if not was_tracing:
28+
tracemalloc.stop()
29+
performance.counter += 1
30+
performance.total_time += t1 - t0
31+
performance.total_mem += max(peak - mem_before, 0)

0 commit comments

Comments
 (0)