File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 1+ import time
2+ import tracemalloc
3+
4+ def performance (fn ):
5+ """
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+
22+ def wrapper (* args , ** kwargs ):
23+ tracemalloc .start ()
24+
25+ time_before = time .time ()
26+
27+ result = fn (* args , ** kwargs )
28+
29+ time_after = time .time ()
30+
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
39+
40+ return wrapper
You can’t perform that action at this time.
0 commit comments