File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change 1+ import time
2+ import psutil
3+
4+ total_time = 0
5+ total_mem = 0
6+ counter = 0
7+
8+ def performance (fn ):
9+ """
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+ """
36+ def wrapper (* args , ** kwargs ):
37+ global total_time , total_mem , counter
38+ process = psutil .Process ()
39+
40+ mem_before = process .memory_info ().rss
41+ time_before = time .time ()
42+
43+ counter += 1
44+ fn (* args , ** kwargs )
45+
46+ time_after = time .time ()
47+ total_time += time_after - time_before
48+
49+ mem_after = process .memory_info ().rss
50+ total_mem += mem_after - mem_before
51+
52+ return wrapper
You can’t perform that action at this time.
0 commit comments