|
1 | 1 | import time |
2 | | -import tracemalloc |
| 2 | +import sys |
3 | 3 |
|
4 | 4 | def performance(func): |
| 5 | + |
| 6 | + if not hasattr(performance, 'counter'): |
| 7 | + setattr(performance, 'counter', 0) |
| 8 | + |
| 9 | + if not hasattr(performance, 'total_time'): |
| 10 | + setattr(performance, 'total_time', 0.0) |
5 | 11 |
|
6 | | - def wrapper(*args, **kwargs): |
7 | | - if not hasattr(wrapper, "counter"): |
8 | | - wrapper.counter = 0 |
9 | | - wrapper.total_time = 0 |
10 | | - wrapper.total_mem = 0 |
| 12 | + if not hasattr(performance, 'total_mem'): |
| 13 | + setattr(performance, 'total_mem', 0) |
11 | 14 |
|
12 | | - tracemalloc.start() |
13 | | - start_time = time.time() |
14 | | - |
15 | | - result = func(*args, **kwargs) |
16 | | - |
17 | | - time_taken = time.time() - start_time |
18 | | - current_mem, peak_mem = tracemalloc.get_traced_memory() |
19 | | - tracemalloc.stop() |
20 | | - |
21 | | - wrapper.counter += 1 |
22 | | - wrapper.total_time += time_taken |
23 | | - wrapper.total_mem += peak_mem |
24 | | - |
25 | | - print(f"'{func.__name__}' was called {wrapper.counter} times.") |
26 | | - print(f"Total time so far: {wrapper.total_time:.4f} seconds.") |
27 | | - print(f"Total peak memory used: {wrapper.total_mem / 1024:.2f} KB.\n") |
| 15 | + def wrapper(*args, **kwargs): |
| 16 | + start_time = time.time() |
| 17 | + memory_usage=sys.getsizeof(func(*args, **kwargs)) |
| 18 | + end_time = time.time() |
| 19 | + |
| 20 | + setattr(performance, 'counter', getattr(performance, 'counter') + 1) |
| 21 | + setattr(performance, 'total_time', getattr(performance, 'total_time') + (end_time - start_time)) |
| 22 | + setattr(performance, 'total_mem', getattr(performance, 'total_mem') + memory_usage) |
28 | 23 |
|
29 | | - return result |
| 24 | + return func(*args, **kwargs) |
30 | 25 |
|
31 | 26 | return wrapper |
0 commit comments