|
1 | 1 | import time
|
2 |
| -import psutil |
3 |
| - |
4 |
| -total_time = 0 |
5 |
| -total_mem = 0 |
6 |
| -counter = 0 |
| 2 | +import tracemalloc |
7 | 3 |
|
8 | 4 | def performance(fn):
|
9 | 5 | """
|
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 | + |
36 | 22 | def wrapper(*args, **kwargs):
|
37 |
| - global total_time, total_mem, counter |
38 |
| - process = psutil.Process() |
| 23 | + tracemalloc.start() |
39 | 24 |
|
40 |
| - mem_before = process.memory_info().rss |
41 | 25 | time_before = time.time()
|
42 | 26 |
|
43 |
| - counter += 1 |
44 |
| - fn(*args, **kwargs) |
| 27 | + result = fn(*args, **kwargs) |
45 | 28 |
|
46 | 29 | time_after = time.time()
|
47 |
| - total_time += time_after - time_before |
48 | 30 |
|
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 |
51 | 39 |
|
52 | 40 | return wrapper
|
0 commit comments