Skip to content

Commit 314704c

Browse files
Decorator for function metrics
1 parent 71f5b39 commit 314704c

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import time
2+
import tracemalloc
3+
import functools
4+
5+
def performance(func):
6+
"""
7+
A decorator that measures the execution time, memory usage,
8+
and call count of the decorated functions.
9+
"""
10+
@functools.wraps(func)
11+
def wrapper(*args, **kwargs):
12+
# Increment the global counter for the decorator
13+
performance.counter += 1
14+
15+
# Start tracking memory
16+
tracemalloc.start()
17+
# Start tracking time
18+
start_time = time.perf_counter()
19+
20+
try:
21+
# Execute the actual function
22+
result = func(*args, **kwargs)
23+
finally:
24+
# Calculate elapsed time
25+
end_time = time.perf_counter()
26+
elapsed_time = end_time - start_time
27+
28+
# Get memory usage (current, peak)
29+
current_mem, peak_mem = tracemalloc.get_traced_memory()
30+
31+
# Stop tracking memory
32+
tracemalloc.stop()
33+
34+
# Update global stats
35+
performance.total_time += elapsed_time
36+
performance.total_mem += peak_mem
37+
38+
return result
39+
40+
return wrapper
41+
42+
# Initialize the static attributes on the function object itself
43+
# This allows all decorated functions to share these counters.
44+
performance.counter = 0
45+
performance.total_time = 0
46+
performance.total_mem = 0

0 commit comments

Comments
 (0)