benchmark.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. #!/usr/bin/env python3
  2. import os
  3. import gc
  4. import subprocess
  5. import csv
  6. import sys
  7. import time
  8. import signal
  9. import re
  10. import importlib.util
  11. from argparse import ArgumentParser
  12. from pathlib import Path
  13. from model_properties import model_properties
  14. MODEL_TYPES = ("LI", "HI", "HO", "HOmod")
  15. DS_MODEL_TYPES = ("LI2HI", "HI2LI", "LI-HI", "dLI", "mdLI", "dHI", "mdHI", "dHO", "mdHO", "test")
  16. GEN_METHODS = ("start", "uniform", "end")
  17. INT_CYCLES = 0
  18. EXT_CYCLES = 0
  19. PyPDEVS = "./pythonpdevs/main.py"
  20. MinimalPyPDEVS = "./pythonpdevs-minimal/main.py"
  21. # Regex to capture times from script output
  22. TIME_PATTERN = re.compile(
  23. r"Model creation time: ([\d.eE+-]+).*"
  24. r"Engine setup time: ([\d.eE+-]+).*"
  25. r"Simulation time: ([\d.eE+-]+)",
  26. re.S
  27. )
  28. def create_graph(file, title=None):
  29. # Base command
  30. cmd = f"procpath plot -d {file} -f {file.with_suffix('.svg')} -q rss --relative-time"
  31. # Add title if provided
  32. if title:
  33. cmd += f" --title '{title}'"
  34. subprocess.run(cmd, shell=True)
  35. def run_devstone(run_simulation_func, model_type, depth, width, mode, out, mem_cmd, stats, DCP, *, classic=False, number=1, gen_mode="uniform"):
  36. """Runs the simulation function in-process and handles memory profiling asynchronously if needed."""
  37. gc.collect()
  38. pp_proc = None
  39. if mem_cmd:
  40. my_pid = os.getpid()
  41. query = f"$..children[?(@.stat.pid == {my_pid})]"
  42. cmd = [
  43. "python", "-m", "procpath", "record",
  44. "-i", str(mem_cmd["interval"]),
  45. "-f", "stat",
  46. "-d", str(mem_cmd["file"]),
  47. query
  48. ]
  49. pp_proc = subprocess.Popen(cmd)
  50. try:
  51. creation, setup, sim = run_simulation_func(
  52. model_type=model_type,
  53. depth=depth,
  54. width=width,
  55. int_cycles=INT_CYCLES,
  56. ext_cycles=EXT_CYCLES,
  57. dcp=DCP,
  58. stats=stats,
  59. dynamic=(mode == "dynamic"),
  60. classic=classic,
  61. number=number,
  62. gen_mode=gen_mode
  63. )
  64. except Exception as e:
  65. print(f"Simulation execution failed: {e}")
  66. creation, setup, sim = None, None, None
  67. if pp_proc:
  68. pp_proc.send_signal(signal.SIGINT)
  69. pp_proc.wait()
  70. if os.path.exists(mem_cmd["file"]) and os.path.getsize(mem_cmd["file"]) > 0:
  71. props = model_properties(model_type, width, depth)
  72. n_atomic = props.get("Atomic Models", "0")
  73. graph_title = f"{model_type} ({int(n_atomic)} atomic models)"
  74. create_graph(Path(mem_cmd["file"]), graph_title)
  75. else:
  76. print(f"Warning: Memory database {mem_cmd['file']} is empty after simulation.")
  77. return creation, setup, sim
  78. def defaultArguments(parser):
  79. parser.add_argument("-p", "--path", type=Path, default=Path("./Results/PyPDEVS"), help="Path to the results directory")
  80. parser.add_argument("-f", '--filename', type=str, default="", help="Name of the output file")
  81. parser.add_argument("-a", "--append", action="store_true", help="Append to the output file instead of overwriting.")
  82. parser.add_argument("-D", "--max-depth", default=8, type=int, help="Max depth for the generated models")
  83. parser.add_argument("-ds", "--depth-stepsize", type=int, help="Determines for which depths a model is generated.")
  84. parser.add_argument("-W", "--max-width", default=8, type=int, help="Max width for the generated models")
  85. parser.add_argument("-ws", "--width-stepsize", type=int, help="Determines for which depths a model is generated.")
  86. parser.add_argument("-r", "--repetitions", default=1, type=int, help="The number of times a simulation is repeated")
  87. parser.add_argument("-O", "--output", action="store_true", help="Print Simulation Outputs")
  88. parser.add_argument("-M", "--memory", action="store_true", help="Measures the memory usage of a simulation.")
  89. parser.add_argument("-i", "--interval", default=1.0, type=float, help="The interval at which measurements are taken.")
  90. parser.add_argument("--stats", "-s", action="store_true", help="Enable Event Tracking")
  91. parser.add_argument("--DCP", choices=["old", "memoised"], default="", help="Select the DCP implementation, old: legacy, memoised: cached, and leave empty to use the default one.")
  92. def Minimal(subparsers):
  93. minimal = subparsers.add_parser("minimal", help="Minimal DEVS kernel")
  94. minimal.set_defaults(mode="minimal")
  95. defaultArguments(minimal)
  96. minimal.add_argument(
  97. "-ms", "--model-structure",
  98. nargs="+",
  99. choices=MODEL_TYPES,
  100. default=MODEL_TYPES
  101. )
  102. def Classic(subparsers):
  103. classic = subparsers.add_parser("classic", help="Classic DEVS Simulator")
  104. classic.set_defaults(mode="classic")
  105. defaultArguments(classic)
  106. classic.add_argument(
  107. "-ms", "--model-structure",
  108. nargs="+",
  109. choices=MODEL_TYPES,
  110. default=MODEL_TYPES
  111. )
  112. def Parallel(subparsers):
  113. parallel = subparsers.add_parser("parallel", help="Parallel DEVS")
  114. parallel.set_defaults(mode="parallel")
  115. defaultArguments(parallel)
  116. parallel.add_argument(
  117. "-ms", "--model-structure",
  118. nargs="+",
  119. choices=MODEL_TYPES,
  120. default=MODEL_TYPES
  121. )
  122. def Dynamic(subparsers):
  123. dynamic = subparsers.add_parser("dynamic", help="Dynamic Structure DEVS")
  124. dynamic.set_defaults(mode="dynamic")
  125. defaultArguments(dynamic)
  126. dynamic.add_argument(
  127. "-ms", "--model-structure",
  128. nargs="+",
  129. choices=MODEL_TYPES + DS_MODEL_TYPES,
  130. default=MODEL_TYPES + DS_MODEL_TYPES
  131. )
  132. dynamic.add_argument(
  133. "-C", "--classic",
  134. action="store_true",
  135. default=False,
  136. help="Selects the Classic DEVS Simulator"
  137. )
  138. dynamic.add_argument(
  139. "-n", "--number",
  140. default=1,
  141. type=int,
  142. help="Number of models to be generated in a cycle per coupled model")
  143. dynamic.add_argument(
  144. "-g", "--gen-mode",
  145. choices=GEN_METHODS,
  146. default="uniform"
  147. )
  148. def parse_args():
  149. parser = ArgumentParser()
  150. subparsers = parser.add_subparsers(dest="mode")
  151. Minimal(subparsers)
  152. Parallel(subparsers)
  153. Classic(subparsers)
  154. Dynamic(subparsers)
  155. args = parser.parse_args()
  156. if args.depth_stepsize is None:
  157. args.depth_stepsize = args.max_depth
  158. if args.width_stepsize is None:
  159. args.width_stepsize = args.max_width
  160. if args.memory or args.stats:
  161. args.output = True
  162. return args
  163. def run(writer, csvfile, model_type, d, w, args, mem_cmd, extra, run_simulation_func):
  164. """Orchestrates repeated simulation runs with an active JIT warmup cycle."""
  165. for depth in range(d[1], d[0] + 1, d[1]):
  166. for width in range(w[1], w[0] + 1, w[1]):
  167. # --- JIT Warmup Run (Matches Julia's warmup step) ---
  168. if args.output:
  169. print(f"Warming up PyPy JIT for {model_type} (D:{depth}, W:{width})")
  170. # Execute an unrecorded, clean warmup pass to compile hot paths
  171. run_devstone(
  172. run_simulation_func, model_type, depth, width,
  173. args.mode, args.output,
  174. {}, False, args.DCP, **extra
  175. )
  176. # --- Measured Repetitions Loop ---
  177. for run_idx in range(args.repetitions):
  178. if args.output or args.stats:
  179. print(f"Running {model_type} (D:{depth}, W:{width}) - Repetition {run_idx}...")
  180. creation, setup, sim = run_devstone(
  181. run_simulation_func, model_type, depth, width,
  182. args.mode, args.output,
  183. mem_cmd, args.stats, args.DCP,
  184. **extra
  185. )
  186. if writer and creation is not None:
  187. row = {
  188. "simulator": sim_id,
  189. "model_type": model_type, "depth": depth, "width": width, "run": run_idx,
  190. "creation_time": creation, "setup_time": setup, "simulation_time": sim,
  191. }
  192. if args.mode == "dynamic":
  193. row["number"] = args.number
  194. row["generator_mode"] = args.gen_mode
  195. writer.writerow(row)
  196. csvfile.flush()
  197. if args.output or args.stats:
  198. if creation is not None:
  199. print(f"\tCreation: {creation:.4f}s | Setup: {setup:.4f}s | Sim: {sim:.4f}s")
  200. if __name__ == "__main__":
  201. args = parse_args()
  202. print(args)
  203. d = (args.max_depth, args.depth_stepsize)
  204. w = (args.max_width, args.width_stepsize)
  205. if d[0] % d[1] != 0:
  206. raise RuntimeError("Invalid depth stepsize.")
  207. if w[0] % w[1] != 0:
  208. raise RuntimeError("Invalid width stepsize.")
  209. fieldnames = ["simulator", "model_type", "depth", "width", "run",
  210. "creation_time", "setup_time", "simulation_time"]
  211. mode = args.mode
  212. if mode == "dynamic":
  213. if args.classic:
  214. mode += "-classic"
  215. fieldnames += ["number", "generator_mode"]
  216. sim_id = f"pypdevs-{mode}"
  217. extra = {
  218. "classic": False if not hasattr(args, "classic") else args.classic,
  219. "gen_mode": "uniform" if not hasattr(args, "gen_mode") else args.gen_mode,
  220. "number": 1 if not hasattr(args, "number") else args.number,
  221. }
  222. time_dir = args.path / "Time" / mode
  223. time_dir.mkdir(parents=True, exist_ok=True)
  224. mem_dir = args.path / "Memory" / mode
  225. mem_dir.mkdir(parents=True, exist_ok=True)
  226. SCRIPT_PATH = MinimalPyPDEVS if args.mode == "minimal" else PyPDEVS
  227. script_path_obj = Path(SCRIPT_PATH)
  228. script_dir = str(script_path_obj.parent.resolve())
  229. if script_dir not in sys.path:
  230. sys.path.insert(0, script_dir)
  231. project_root = os.path.abspath(os.path.join(os.getcwd(), ".."))
  232. if project_root not in sys.path:
  233. sys.path.insert(0, project_root)
  234. spec = importlib.util.spec_from_file_location("sim_main", SCRIPT_PATH)
  235. sim_module = importlib.util.module_from_spec(spec)
  236. sys.modules["sim_main"] = sim_module
  237. spec.loader.exec_module(sim_module)
  238. if not hasattr(sim_module, "run_simulation"):
  239. raise AttributeError(f"The simulation engine at {SCRIPT_PATH} is missing a 'run_simulation' hook.")
  240. run_simulation_func = sim_module.run_simulation
  241. for model_type in args.model_structure:
  242. time_file = (time_dir / model_type).with_suffix(".csv")
  243. memory_file = (mem_dir / model_type).with_suffix(".sqlite")
  244. if hasattr(args, "number") and args.number > 1:
  245. time_file = time_file.with_name(time_file.stem + "-" + str(args.number) + time_file.suffix)
  246. memory_file = memory_file.with_name(memory_file.stem + "-" + str(args.number) + memory_file.suffix)
  247. if args.filename:
  248. suffix = f"_{args.filename}"
  249. time_file = time_file.with_name(time_file.stem + suffix + time_file.suffix)
  250. memory_file = memory_file.with_name(memory_file.stem + suffix + memory_file.suffix)
  251. mem_cmd = {"interval": args.interval, "file": memory_file} if args.memory else {}
  252. if not args.memory:
  253. file_mode = "a" if args.append else "w"
  254. write_header = not args.append or not os.path.exists(time_file)
  255. with open(time_file, file_mode, newline="") as csvfile:
  256. writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
  257. if write_header:
  258. writer.writeheader()
  259. run(writer, csvfile, model_type, d, w, args, mem_cmd, extra, run_simulation_func)
  260. print(f"Saved timing results to {time_file}")
  261. else:
  262. if os.path.exists(memory_file) and not args.append:
  263. os.remove(memory_file)
  264. print("Measuring memory (Timing results will not be saved)...")
  265. run(None, None, model_type, d, w, args, mem_cmd, extra, run_simulation_func)
  266. print(f"Saved memory database to {memory_file}")