Skip to content

Commit 6fd68cf

Browse files
authored
Add files via upload
1 parent 628e8eb commit 6fd68cf

1 file changed

Lines changed: 31 additions & 0 deletions

File tree

‎Week04/decorators_yagiz_cengiz.py‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import functools
2+
import time
3+
import tracemalloc
4+
5+
6+
def performance(fn):
7+
"""
8+
This decorator measures the time and memory of the calls of a function.
9+
The statistics of all decorated functions are saved in its attributes.
10+
"""
11+
12+
@functools.wraps(fn)
13+
def wrapper(*args, **kwargs):
14+
# shortcut: a decorated function calling another one under-reports
15+
# memory because tracemalloc is global, keep calls flat to stay exact
16+
tracemalloc.start()
17+
start = time.perf_counter()
18+
try:
19+
return fn(*args, **kwargs)
20+
finally:
21+
performance.total_time += time.perf_counter() - start
22+
performance.total_mem += tracemalloc.get_traced_memory()[1]
23+
performance.counter += 1
24+
tracemalloc.stop()
25+
26+
return wrapper
27+
28+
29+
performance.counter = 0
30+
performance.total_time = 0
31+
performance.total_mem = 0

0 commit comments

Comments
 (0)