compareMemory.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. #!/usr/bin/env python3
  2. import sqlite3
  3. import pandas as pd
  4. import matplotlib.pyplot as plt
  5. import argparse
  6. from pathlib import Path
  7. from itertools import cycle
  8. from model_properties import model_properties
  9. # Standard Linux page size in bytes
  10. PAGE_SIZE = 4096
  11. SIMULATOR_MAPPING = {
  12. "minimal": "(m)",
  13. "classic": "(c)",
  14. "parallel": "(p)",
  15. "dynamic": "(d)",
  16. "dynamic-classic": "(dc)",
  17. "Memory": "(A)",
  18. }
  19. TIME_UNITS = {"ms": 0.001, "s": 1, "m": 60, "h": 3600}
  20. MEMORY_UNITS = {
  21. "Bytes": 1, "KB": 1000, "MB": 1000 ** 2, "GB": 1000 ** 3,
  22. "KiB": 1024, "MiB": 1024 ** 2, "GiB": 1024 ** 3
  23. }
  24. PREDEFINED_STYLES = {
  25. 'blue': {'color': 'tab:blue', 'ls': '-', 'marker': 'o'},
  26. 'orange': {'color': 'tab:orange', 'ls': '--', 'marker': 's'},
  27. 'green': {'color': 'tab:green', 'ls': '-.', 'marker': '^'},
  28. 'red': {'color': 'tab:red', 'ls': ':', 'marker': 'D'},
  29. 'purple': {'color': 'tab:purple', 'ls': '-', 'marker': 'v'},
  30. 'brown': {'color': 'tab:brown', 'ls': '--', 'marker': 'X'},
  31. }
  32. SHORTHANDS = {
  33. 'b': 'blue',
  34. 'o': 'orange',
  35. 'g': 'green',
  36. 'r': 'red',
  37. 'p': 'purple',
  38. 'br': 'brown'
  39. }
  40. STYLE_KEYS = list(PREDEFINED_STYLES.keys())
  41. VALID_STYLE_INPUTS = list(PREDEFINED_STYLES.keys()) + list(SHORTHANDS.keys())
  42. def get_style_config(user_input):
  43. '''Helper to resolve shorthands and handle case-insensitivity.'''
  44. normalized = user_input.lower()
  45. key = SHORTHANDS.get(normalized, normalized)
  46. return PREDEFINED_STYLES.get(key, PREDEFINED_STYLES['blue'])
  47. def get_memory_trace(db_path):
  48. if not db_path.exists() or db_path.stat().st_size == 0: return None
  49. try:
  50. with sqlite3.connect(db_path) as conn:
  51. query = "SELECT ts, stat_rss FROM record WHERE stat_comm IN ('python3', 'julia') ORDER BY ts ASC"
  52. df = pd.read_sql_query(query, conn)
  53. return df if not df.empty else None
  54. except sqlite3.Error as e:
  55. return None
  56. def process_data(df, mem_unit, time_unit):
  57. start_time = df["ts"].iloc[0]
  58. df["relative_time"] = (df["ts"] - start_time) / TIME_UNITS[time_unit]
  59. df["memory"] = (df["stat_rss"] * PAGE_SIZE) / MEMORY_UNITS[mem_unit]
  60. return df
  61. def plot_traces(files, styles, width=None, depth=None, mem_unit="MB", time_unit="s", path="", name="", title=None, bw=False):
  62. plt.figure(figsize=(10, 6))
  63. style_cycle = cycle(zip(cycle(plt.rcParams['axes.prop_cycle'].by_key()['color'] if not bw else ['black']),
  64. cycle(['-', '--', '-.', ':'])))
  65. plotted_any, models, main_model_type = False, [], None
  66. for i, db_file in enumerate(files):
  67. file = Path(db_file).resolve()
  68. df = get_memory_trace(file)
  69. if df is None: continue
  70. model_type = file.stem
  71. models.append(model_type)
  72. if main_model_type is None: main_model_type = model_type
  73. df = process_data(df, mem_unit, time_unit)
  74. color, linestyle = next(style_cycle)
  75. style_input = styles[i] if i < len(styles) else STYLE_KEYS[i % len(STYLE_KEYS)]
  76. style = get_style_config(style_input)
  77. label = f"{model_type} {SIMULATOR_MAPPING.get(file.parent.name, f'({file.parent.name})')}"
  78. plt.plot(
  79. df["relative_time"],
  80. df["memory"],
  81. label=label,
  82. color=style['color'],
  83. linestyle=style['ls'],
  84. linewidth=1.5
  85. )
  86. plotted_any = True
  87. if not plotted_any: return
  88. plt.xlabel(f"Time ({time_unit})");
  89. plt.ylabel(f"Resident Set Size ({mem_unit})")
  90. if not title:
  91. if main_model_type and width and depth:
  92. props = model_properties(main_model_type, width, depth)
  93. atomics = int(props.get("Atomic Models", 0))
  94. events = int(props.get("Events", 0))
  95. plt.suptitle(f"Memory Usage over Time: {main_model_type}", fontsize=12)
  96. plt.title(f"Width: {width}, Depth: {depth} | #Atomic Models: {atomics:,} | #Events: {events:,}", fontsize=10)
  97. else:
  98. plt.title("Memory Usage over Time", fontsize=12)
  99. else:
  100. plt.title(title, fontsize=12)
  101. plt.legend()
  102. plt.grid(True, linestyle=':', alpha=0.6)
  103. out_dir = Path(__file__).resolve().parent / "MemoryPlots" / path
  104. out_dir.mkdir(parents=True, exist_ok=True)
  105. plt.tight_layout();
  106. plt.savefig(out_dir / f"{name or '|'.join(set(models))}.png", dpi=300)
  107. def main():
  108. parser = argparse.ArgumentParser()
  109. parser.add_argument("files", nargs="+")
  110. parser.add_argument("-w", "--width", type=int)
  111. parser.add_argument("-d", "--depth", type=int)
  112. parser.add_argument('-s', '--styles', type=str, nargs='+', help=f"Space-separated list of colors matching CSV order. Options: {', '.join(VALID_STYLE_INPUTS)}")
  113. parser.add_argument("-mu", "--memory-unit", default="MB")
  114. parser.add_argument("-tu", "--time-unit", default="s")
  115. parser.add_argument("-p", "--path", default="")
  116. parser.add_argument("-n", "--name", default="")
  117. parser.add_argument("-t", "--title")
  118. parser.add_argument("--bw", action="store_true")
  119. args = parser.parse_args()
  120. if not args.styles:
  121. styles = [STYLE_KEYS[i % len(STYLE_KEYS)] for i in range(len(args.files))]
  122. else:
  123. styles = args.styles
  124. plot_traces(args.files, styles, args.width, args.depth, args.memory_unit, args.time_unit, args.path, args.name, args.title,
  125. args.bw)
  126. if __name__ == "__main__": main()