File tree Expand file tree Collapse file tree 1 file changed +53
-0
lines changed
Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Original file line number Diff line number Diff line change 1+ import time
2+ import sys
3+ import functools
4+
5+
6+ class performance :
7+ """
8+ A decorator which measures the performance of functions and saves statistics.
9+
10+ Attributes:
11+ counter: Number of times the decorator has been called
12+ total_time: Total time in seconds that decorated functions took
13+ total_mem: Total memory in bytes that decorated functions consumed
14+ """
15+ counter = 0
16+ total_time = 0
17+ total_mem = 0
18+
19+ def __init__ (self , func ):
20+ """Initialize the decorator with the function to be decorated."""
21+ self .func = func
22+ functools .update_wrapper (self , func )
23+
24+ def __call__ (self , * args , ** kwargs ):
25+ """
26+ Execute the decorated function and track performance metrics.
27+
28+ :param args: Positional arguments for the function
29+ :param kwargs: Keyword arguments for the function
30+ :return: The result of the decorated function
31+ """
32+ # Increment counter
33+ performance .counter += 1
34+
35+ # Measure time
36+ start_time = time .time ()
37+
38+ # Get memory before execution
39+ mem_before = sys .getsizeof (args ) + sys .getsizeof (kwargs )
40+
41+ # Execute the function
42+ result = self .func (* args , ** kwargs )
43+
44+ # Measure time taken
45+ end_time = time .time ()
46+ elapsed_time = end_time - start_time
47+ performance .total_time += elapsed_time
48+
49+ # Get memory after execution (including result)
50+ mem_after = sys .getsizeof (result ) if result is not None else 0
51+ performance .total_mem += mem_after
52+
53+ return result
You can’t perform that action at this time.
0 commit comments