|
| 1 | +import time |
| 2 | +import tracemalloc |
| 3 | + |
| 4 | + |
| 5 | +def performance(func): |
| 6 | + """ |
| 7 | + A decorator to measure the performance of a function. |
| 8 | + Attributes: |
| 9 | + counter: The number of times the function has been called. |
| 10 | + total_time: The total time the function has taken to run. |
| 11 | + total_mem: The total peak memory used by the function in bytes. |
| 12 | + """ |
| 13 | + |
| 14 | + # Initialize attributes if they don't already exist |
| 15 | + if not hasattr(performance, 'counter'): |
| 16 | + performance.counter = 0 |
| 17 | + if not hasattr(performance, 'total_time'): |
| 18 | + performance.total_time = 0.0 |
| 19 | + if not hasattr(performance, 'total_mem'): |
| 20 | + performance.total_mem = 0 |
| 21 | + |
| 22 | + def wrapper(*args, **kwargs): |
| 23 | + # Increment call counter |
| 24 | + performance.counter += 1 |
| 25 | + |
| 26 | + # Measure execution time and memory usage |
| 27 | + start_time = time.time() |
| 28 | + tracemalloc.start() |
| 29 | + |
| 30 | + try: |
| 31 | + result = func(*args, **kwargs) |
| 32 | + except Exception as exc: |
| 33 | + print(f"Error: {exc}") |
| 34 | + result = None |
| 35 | + finally: |
| 36 | + end_time = time.time() |
| 37 | + current, peak = tracemalloc.get_traced_memory() |
| 38 | + tracemalloc.stop() |
| 39 | + |
| 40 | + # Update performance metrics |
| 41 | + time_taken = end_time - start_time |
| 42 | + performance.total_time += time_taken |
| 43 | + performance.total_mem += peak |
| 44 | + |
| 45 | + # Print stats for the current function call |
| 46 | + print(f"{func.__name__}: Calls={performance.counter}, Time={time_taken:.4f}s, " |
| 47 | + f"Memory={peak / 1024:.1f}KB, TotalTime={performance.total_time:.4f}s, " |
| 48 | + f"TotalMem={performance.total_mem / 1024:.1f}KB") |
| 49 | + |
| 50 | + return result |
| 51 | + |
| 52 | + return wrapper |
| 53 | + |
| 54 | + |
| 55 | +@performance |
| 56 | +def example_function(x): |
| 57 | + return x * x |
| 58 | + |
| 59 | + |
| 60 | +@performance |
| 61 | +def memory_intensive_function(size): |
| 62 | + return [0] * size |
| 63 | + |
| 64 | + |
| 65 | +if __name__ == "__main__": |
| 66 | + # Run test functions |
| 67 | + example_function(1) |
| 68 | + example_function(2) |
| 69 | + memory_intensive_function(1000000) |
| 70 | + |
| 71 | + # Display final performance metrics |
| 72 | + print(f"Function called {performance.counter} times.") |
| 73 | + print(f"Total time taken: {performance.total_time:.4f} seconds.") |
| 74 | + print(f"Total memory used: {performance.total_mem / 1024:.2f} KB.") |
0 commit comments