|
| 1 | +import time |
| 2 | +import tracemalloc |
| 3 | + |
| 4 | +def performance(func): |
| 5 | + """ |
| 6 | + A decorator to keep track of how often a function is called, |
| 7 | + how long it takes to run, and how much memory it uses. |
| 8 | + |
| 9 | + Attributes: |
| 10 | + counter: How many times the function has been called. |
| 11 | + total_time: The total time the function has taken to run. |
| 12 | + total_mem: The total memory used by the function. |
| 13 | + """ |
| 14 | + |
| 15 | + # Initialize the counters |
| 16 | + performance.counter = 0 |
| 17 | + performance.total_time = 0 |
| 18 | + performance.total_mem = 0 |
| 19 | + |
| 20 | + def wrapper(*args, **kwargs): |
| 21 | + # Start tracking memory |
| 22 | + tracemalloc.start() |
| 23 | + |
| 24 | + # Record the start time |
| 25 | + start_time = time.time() |
| 26 | + |
| 27 | + # Call the actual function |
| 28 | + result = func(*args, **kwargs) |
| 29 | + |
| 30 | + # Calculate how long it took |
| 31 | + time_taken = time.time() - start_time |
| 32 | + |
| 33 | + # Capture the peak memory usage |
| 34 | + current_mem, peak_mem = tracemalloc.get_traced_memory() |
| 35 | + tracemalloc.stop() |
| 36 | + |
| 37 | + # Update the stats |
| 38 | + performance.counter += 1 |
| 39 | + performance.total_time += time_taken |
| 40 | + performance.total_mem += peak_mem # Peak memory during execution |
| 41 | + |
| 42 | + # Friendly output |
| 43 | + print(f"'{func.__name__}' was called {performance.counter} times.") |
| 44 | + print(f"Total time so far: {performance.total_time:.4f} seconds.") |
| 45 | + print(f"Total memory used: {performance.total_mem / 1024:.2f} KB.\n") |
| 46 | + |
| 47 | + return result |
| 48 | + |
| 49 | + return wrapper |
0 commit comments