|
| 1 | +import time |
| 2 | +import tracemalloc |
| 3 | + |
| 4 | +def performance(function): |
| 5 | + """ |
| 6 | + A decorator to measure the performance of a function. |
| 7 | +
|
| 8 | + Tracks: |
| 9 | + - `counter`: Number of times the function is called. |
| 10 | + - `total_time`: Total execution time in seconds. |
| 11 | + - `total_mem`: Total peak memory usage in bytes (via `tracemalloc`). |
| 12 | +
|
| 13 | + Args: |
| 14 | + function (callable): The function to be measured. |
| 15 | +
|
| 16 | + Returns: |
| 17 | + callable: The wrapped function with performance tracking. |
| 18 | + """ |
| 19 | + if not hasattr(performance, 'counter'): |
| 20 | + setattr(performance, 'counter', 0) |
| 21 | + |
| 22 | + if not hasattr(performance, 'total_time'): |
| 23 | + setattr(performance, 'total_time', 0.0) |
| 24 | + |
| 25 | + if not hasattr(performance, 'total_mem'): |
| 26 | + setattr(performance, 'total_mem', 0.0) |
| 27 | + |
| 28 | + def wrapper(*args, **kwargs): |
| 29 | + tracemalloc.start() |
| 30 | + start_time = time.time() |
| 31 | + result = function(*args, **kwargs) |
| 32 | + end_time = time.time() |
| 33 | + elapsed_time = end_time - start_time |
| 34 | + current, peak = tracemalloc.get_traced_memory() |
| 35 | + tracemalloc.stop() |
| 36 | + setattr(performance, 'counter', getattr(performance, 'counter') + 1) |
| 37 | + setattr(performance, 'total_time', getattr(performance, 'total_time') + elapsed_time) |
| 38 | + setattr(performance, 'total_mem', getattr(performance, 'total_mem') + peak) |
| 39 | + return result |
| 40 | + |
| 41 | + return wrapper |
0 commit comments