-
Notifications
You must be signed in to change notification settings - Fork 183
Expand file tree
/
Copy pathdecorators_emine_cetin.py
More file actions
46 lines (37 loc) · 1.32 KB
/
decorators_emine_cetin.py
File metadata and controls
46 lines (37 loc) · 1.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import time
import tracemalloc
import functools
def performance(func):
"""
A decorator that measures the execution time, memory usage,
and call count of the decorated functions.
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
# Increment the global counter for the decorator
performance.counter += 1
# Start tracking memory
tracemalloc.start()
# Start tracking time
start_time = time.perf_counter()
try:
# Execute the actual function
result = func(*args, **kwargs)
finally:
# Calculate elapsed time
end_time = time.perf_counter()
elapsed_time = end_time - start_time
# Get memory usage (current, peak)
current_mem, peak_mem = tracemalloc.get_traced_memory()
# Stop tracking memory
tracemalloc.stop()
# Update global stats
performance.total_time += elapsed_time
performance.total_mem += peak_mem
return result
return wrapper
# Initialize the static attributes on the function object itself
# This allows all decorated functions to share these counters.
performance.counter = 0
performance.total_time = 0
performance.total_mem = 0