1+ import tracemalloc
2+ import time
3+
4+ def performance (func ):
5+ """
6+ Decorator to measure the performance of a function in terms of
7+ execution time and memory usage.
8+
9+ Attributes:
10+ counter (int): Counts the number of times the decorated function has been called.
11+ total_time (float): Accumulates the total execution time of the function calls.
12+ total_mem (int): Accumulates the total memory used (in bytes) by the function calls.
13+
14+ Args:
15+ func (function): The function to be decorated.
16+
17+ Returns:
18+ function: The wrapped function with performance tracking.
19+ """
20+
21+ # Initialize performance attributes
22+ performance .counter = 0
23+ performance .total_time = 0
24+ performance .total_mem = 0
25+
26+ def _wrapper (* args , ** kwargs ):
27+ """
28+ Wrapper function that measures and accumulates the performance
29+ metrics of the decorated function.
30+
31+ Args:
32+ *args: Variable length argument list for the decorated function.
33+ **kwargs: Arbitrary keyword arguments for the decorated function.
34+
35+ Returns:
36+ function: The result returned by the decorated function.
37+ """
38+
39+ performance .counter += 1
40+ start_time = time .time ()
41+ tracemalloc .start ()
42+ snapshot1 = tracemalloc .take_snapshot ()
43+
44+ result = func (* args , ** kwargs )
45+
46+ snapshot2 = tracemalloc .take_snapshot ()
47+ tracemalloc .stop ()
48+ end_time = time .time ()
49+
50+ # Calculate the memory difference and accumulate it
51+ performance .total_time += end_time - start_time
52+ performance .total_mem += snapshot2 .compare_to (snapshot1 , "lineno" )[0 ].size_diff
53+
54+ return result
55+
56+ return _wrapper
0 commit comments