Skip to content

Commit cb4f1cb

Browse files
authored
Refactor performance decorator to use static variables
1 parent 85c7cbf commit cb4f1cb

1 file changed

Lines changed: 16 additions & 26 deletions

File tree

‎Week04/decorators_ilyas_bugra_filoglu‎

Lines changed: 16 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -3,39 +3,29 @@ import tracemalloc
33
from functools import wraps
44

55
def performance(func):
6-
call_count = 0
7-
total_time = 0.0
8-
total_mem = 0
6+
# initialize stats on the decorator itself
7+
if not hasattr(performance, "counter"):
8+
performance.counter = 0
9+
if not hasattr(performance, "total_time"):
10+
performance.total_time = 0.0
11+
if not hasattr(performance, "total_mem"):
12+
performance.total_mem = 0
913

1014
@wraps(func)
1115
def wrapper(*args, **kwargs):
12-
nonlocal call_count, total_time, total_mem
13-
14-
tracing_started = tracemalloc.is_tracing()
15-
16-
if not tracing_started:
17-
tracemalloc.start()
18-
16+
tracemalloc.start()
1917
tracemalloc.reset_peak()
20-
start_time = time.perf_counter()
18+
start = time.perf_counter()
2119

2220
try:
23-
result = func(*args, **kwargs)
24-
return result
25-
21+
return func(*args, **kwargs)
2622
finally:
27-
end_time = time.perf_counter()
28-
current_mem, peak_mem = tracemalloc.get_traced_memory()
29-
30-
call_count += 1
31-
total_time += end_time - start_time
32-
total_mem += peak_mem
33-
34-
if not tracing_started:
35-
tracemalloc.stop()
23+
elapsed = time.perf_counter() - start
24+
_, peak = tracemalloc.get_traced_memory()
25+
tracemalloc.stop()
3626

37-
wrapper.call_count = lambda: call_count
38-
wrapper.total_time = lambda: total_time
39-
wrapper.total_mem = lambda: total_mem
27+
performance.counter += 1
28+
performance.total_time += elapsed
29+
performance.total_mem += peak
4030

4131
return wrapper

0 commit comments

Comments
 (0)