|
| 1 | +import time |
| 2 | +import tracemalloc |
| 3 | +import linecache |
| 4 | +import os |
| 5 | + |
| 6 | + |
| 7 | +class Timer: |
| 8 | + """Timer for timing operations.""" |
| 9 | + |
| 10 | + def __init__(self): |
| 11 | + self.start = None |
| 12 | + self.end = None |
| 13 | + |
| 14 | + def __enter__(self): |
| 15 | + self.start = time.time() |
| 16 | + return self |
| 17 | + |
| 18 | + def __exit__(self, exc_type, exc_val, exc_tb): |
| 19 | + self.end = time.time() |
| 20 | + return False |
| 21 | + |
| 22 | + @property |
| 23 | + def time(self) -> float: |
| 24 | + if self.start is None or self.end is None: |
| 25 | + raise ValueError("Timer is still running!") |
| 26 | + return self.end - self.start |
| 27 | + |
| 28 | + |
| 29 | +def display_top_memory(snapshot, key_type="lineno", limit=3): |
| 30 | + snapshot = snapshot.filter_traces( |
| 31 | + ( |
| 32 | + tracemalloc.Filter(False, "<frozen importlib._bootstrap>"), |
| 33 | + tracemalloc.Filter(False, "<unknown>"), |
| 34 | + ) |
| 35 | + ) |
| 36 | + top_stats = snapshot.statistics(key_type) |
| 37 | + |
| 38 | + print("Top %s lines" % limit) |
| 39 | + for index, stat in enumerate(top_stats[:limit], 1): |
| 40 | + frame = stat.traceback[0] |
| 41 | + # replace "/path/to/module/file.py" with "module/file.py" |
| 42 | + filename = os.sep.join(frame.filename.split(os.sep)[-2:]) |
| 43 | + print("#%s: %s:%s: %.1f KiB" % (index, filename, frame.lineno, stat.size / 1024)) |
| 44 | + line = linecache.getline(frame.filename, frame.lineno).strip() |
| 45 | + if line: |
| 46 | + print(" %s" % line) |
| 47 | + |
| 48 | + other = top_stats[limit:] |
| 49 | + if other: |
| 50 | + size = sum(stat.size for stat in other) |
| 51 | + print("%s other: %.1f KiB" % (len(other), size / 1024)) |
| 52 | + total = sum(stat.size for stat in top_stats) |
| 53 | + print("Total allocated size: %.1f KiB" % (total / 1024)) |
| 54 | + |
| 55 | + |
| 56 | +def total_memory_usage(snapshot, key_type="lineno"): |
| 57 | + """Extract total memory usage in KiB.""" |
| 58 | + snapshot = snapshot.filter_traces( |
| 59 | + ( |
| 60 | + tracemalloc.Filter(False, "<frozen importlib._bootstrap>"), |
| 61 | + tracemalloc.Filter(False, "<unknown>"), |
| 62 | + ) |
| 63 | + ) |
| 64 | + top_stats = snapshot.statistics(key_type) |
| 65 | + total = sum(stat.size for stat in top_stats) |
| 66 | + return total / 1024 |
| 67 | + |
| 68 | + |
| 69 | +class MemoryTracer: |
| 70 | + def __init__(self): |
| 71 | + self.snapshot = None |
| 72 | + |
| 73 | + def __enter__(self): |
| 74 | + tracemalloc.start() |
| 75 | + return self |
| 76 | + |
| 77 | + def __exit__(self, exc_type, exc_val, exc_tb): |
| 78 | + self.snapshot = tracemalloc.take_snapshot() |
| 79 | + tracemalloc.clear_traces() |
| 80 | + return False |
| 81 | + |
| 82 | + def display_top(self): |
| 83 | + if self.snapshot is None: |
| 84 | + raise ValueError("Memory tracing still running!") |
| 85 | + display_top_memory(self.snapshot) |
| 86 | + |
| 87 | + @property |
| 88 | + def total(self): |
| 89 | + if self.snapshot is None: |
| 90 | + raise ValueError("Memory tracing still running!") |
| 91 | + return total_memory_usage(self.snapshot) |
0 commit comments