Skip to content

Commit d1f313f

Browse files
authored
Create decorators_pelin_akkus,py
1 parent bf48cc8 commit d1f313f

1 file changed

Lines changed: 31 additions & 0 deletions

File tree

‎Week04/decorators_pelin_akkus,py‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
from functools import wraps
2+
from time import perf_counter
3+
import tracemalloc
4+
5+
def performance(func):
6+
"""Track how many times a function runs, its time and memory use."""
7+
8+
@wraps(func)
9+
def wrapper(*args, **kwargs):
10+
wrapper.counter += 1
11+
was_tracing = tracemalloc.is_tracing()
12+
if not was_tracing:
13+
tracemalloc.start()
14+
15+
# Check the memory usage before running the function.
16+
memory_before, _ = tracemalloc.get_traced_memory()
17+
start_time = perf_counter()
18+
19+
try:
20+
return func(*args, **kwargs)
21+
finally:
22+
wrapper.total_time += perf_counter() - start_time
23+
_, peak_memory = tracemalloc.get_traced_memory()
24+
wrapper.total_mem += max(0, peak_memory - memory_before)
25+
if not was_tracing:
26+
tracemalloc.stop()
27+
28+
wrapper.counter = 0
29+
wrapper.total_time = 0.0
30+
wrapper.total_mem = 0
31+
return wrapper

0 commit comments

Comments
 (0)