Skip to content

Commit dbf9da0

Browse files
authored
Update decorators_gokay_sahin.py
1 parent bc37706 commit dbf9da0

File tree

1 file changed

+27
-39
lines changed

1 file changed

+27
-39
lines changed

Week04/decorators_gokay_sahin.py

Lines changed: 27 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,52 +1,40 @@
11
import time
2-
import psutil
3-
4-
total_time = 0
5-
total_mem = 0
6-
counter = 0
2+
import tracemalloc
73

84
def performance(fn):
95
"""
10-
A decorator function to measure the performance of a given function by tracking
11-
both its execution time and memory usage.
12-
13-
This decorator calculates the time taken for the function to run and the
14-
memory used before and after its execution. It also maintains a global counter
15-
of how many times the decorated function has been called, along with
16-
accumulating the total time and memory usage.
17-
18-
:param fn: Function to be decorated and monitored.
19-
:type fn: Callable
20-
:return: A wrapper function that monitors performance of the original function.
21-
:rtype: Callable
22-
23-
Global Variables:
24-
- **total_time** (float): Accumulates the total execution time across all invocations.
25-
- **total_mem** (int): Accumulates the total memory difference across all invocations.
26-
- **counter** (int): Tracks how many times the decorated function has been executed.
27-
28-
Example usage::
29-
30-
@performance
31-
def my_function():
32-
pass
33-
34-
my_function()
35-
"""
6+
Decorator to measure performance of a function, including
7+
execution time and memory usage.
8+
9+
This decorator tracks:
10+
- The number of times the function is called.
11+
- The cumulative time taken by the function.
12+
- The cumulative peak memory usage.
13+
14+
:param fn: The function to be wrapped and measured.
15+
:return: The result of the wrapped function.
16+
"""
17+
if not hasattr(performance, 'counter'):
18+
performance.counter = 0
19+
performance.total_time = 0
20+
performance.total_mem = 0
21+
3622
def wrapper(*args, **kwargs):
37-
global total_time, total_mem, counter
38-
process = psutil.Process()
23+
tracemalloc.start()
3924

40-
mem_before = process.memory_info().rss
4125
time_before = time.time()
4226

43-
counter += 1
44-
fn(*args, **kwargs)
27+
result = fn(*args, **kwargs)
4528

4629
time_after = time.time()
47-
total_time += time_after - time_before
4830

49-
mem_after = process.memory_info().rss
50-
total_mem += mem_after - mem_before
31+
curr_mem, peak_mem = tracemalloc.get_traced_memory()
32+
tracemalloc.stop()
33+
34+
performance.counter += 1
35+
performance.total_time += (time_after - time_before)
36+
performance.total_mem += peak_mem
37+
38+
return result
5139

5240
return wrapper

0 commit comments

Comments
 (0)