Skip to content

Commit 899090b

Browse files
authored
Add performance decorator for timing and memory usage
This decorator tracks the execution time and memory usage of functions, storing statistics in performance.counter, performance.total_time, and performance.total_mem.
1 parent 589b917 commit 899090b

1 file changed

Lines changed: 31 additions & 0 deletions

File tree

‎Week04/decorators_esra_sepik.py‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import time
2+
import tracemalloc
3+
4+
5+
def performance(fn):
6+
"""
7+
Decorator that measures the execution time and memory usage of a function.
8+
Statistics are kept in performance.counter, performance.total_time
9+
and performance.total_mem.
10+
"""
11+
def _inner(*args, **kwargs):
12+
tracemalloc.start()
13+
begin = time.time()
14+
output = fn(*args, **kwargs)
15+
end = time.time()
16+
used = tracemalloc.get_traced_memory()[1]
17+
tracemalloc.stop()
18+
19+
setattr(performance, "counter", getattr(performance, "counter", 0) + 1)
20+
setattr(performance, "total_time", getattr(performance, "total_time", 0) + (end - begin))
21+
setattr(performance, "total_mem", getattr(performance, "total_mem", 0) + used)
22+
return output
23+
24+
_inner.__name__ = fn.__name__
25+
_inner.__doc__ = fn.__doc__
26+
return _inner
27+
28+
29+
performance.counter = 0
30+
performance.total_time = 0
31+
performance.total_mem = 0

0 commit comments

Comments
 (0)