Skip to content

Commit 9b77cd3

Browse files
Implement function call counter and performance decorators
Added two decorators: fn_w_counter for counting function calls and performance for measuring execution time and memory usage.
1 parent f083b29 commit 9b77cd3

1 file changed

Lines changed: 44 additions & 0 deletions

File tree

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import time
2+
import tracemalloc
3+
from functools import wraps
4+
5+
6+
def fn_w_counter(func):
7+
@wraps(func)
8+
def wrapper(*args, **kwargs):
9+
wrapper.counter += 1
10+
11+
caller = func.__globals__.get("__name__", "__main__")
12+
wrapper.callers[caller] = wrapper.callers.get(caller, 0) + 1
13+
14+
result = func(*args, **kwargs)
15+
return result
16+
17+
wrapper.counter = 0
18+
wrapper.callers = {}
19+
return wrapper
20+
21+
22+
def performance(func):
23+
@wraps(func)
24+
def wrapper(*args, **kwargs):
25+
start_time = time.perf_counter()
26+
27+
tracemalloc.start()
28+
result = func(*args, **kwargs)
29+
current_mem, peak_mem = tracemalloc.get_traced_memory()
30+
tracemalloc.stop()
31+
32+
elapsed_time = time.perf_counter() - start_time
33+
34+
wrapper.counter += 1
35+
wrapper.total_time += elapsed_time
36+
wrapper.total_mem += peak_mem
37+
38+
return result
39+
40+
wrapper.counter = 0
41+
wrapper.total_time = 0.0
42+
wrapper.total_mem = 0
43+
44+
return wrapper

0 commit comments

Comments
 (0)