Skip to content

Commit 650b984

Browse files
authored
Merge pull request #650 from erenyurtcu/patch-4
Create decorators_ismeteren_yurtcu.py
2 parents 016e01b + 86413cb commit 650b984

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
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+
4+
def performance(function):
5+
"""
6+
A decorator to measure the performance of a function.
7+
8+
Tracks:
9+
- `counter`: Number of times the function is called.
10+
- `total_time`: Total execution time in seconds.
11+
- `total_mem`: Total peak memory usage in bytes (via `tracemalloc`).
12+
13+
Args:
14+
function (callable): The function to be measured.
15+
16+
Returns:
17+
callable: The wrapped function with performance tracking.
18+
"""
19+
if not hasattr(performance, 'counter'):
20+
setattr(performance, 'counter', 0)
21+
22+
if not hasattr(performance, 'total_time'):
23+
setattr(performance, 'total_time', 0.0)
24+
25+
if not hasattr(performance, 'total_mem'):
26+
setattr(performance, 'total_mem', 0.0)
27+
28+
def wrapper(*args, **kwargs):
29+
tracemalloc.start()
30+
start_time = time.time()
31+
result = function(*args, **kwargs)
32+
end_time = time.time()
33+
elapsed_time = end_time - start_time
34+
current, peak = tracemalloc.get_traced_memory()
35+
tracemalloc.stop()
36+
setattr(performance, 'counter', getattr(performance, 'counter') + 1)
37+
setattr(performance, 'total_time', getattr(performance, 'total_time') + elapsed_time)
38+
setattr(performance, 'total_mem', getattr(performance, 'total_mem') + peak)
39+
return result
40+
41+
return wrapper

0 commit comments

Comments
 (0)