benchmark_schelling.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import timeit
  2. import random
  3. import argparse
  4. import os
  5. import sys
  6. # 1. Catch the argument BEFORE importing the models to avoid the import trap
  7. if "-M" in sys.argv or "--minimal" in sys.argv:
  8. os.environ["PYPDEVS_MINIMAL"] = "1"
  9. else:
  10. os.environ["PYPDEVS_MINIMAL"] = "0"
  11. from pypdevs.simulator import Simulator
  12. from pypdevs.minimal import Simulator as Minimal
  13. from Schelling import Schelling
  14. def runthemodel(seed, dimension, num_agents, radius, threshold, minimal=False):
  15. model = Schelling(
  16. dim=dimension,
  17. num_agents=num_agents,
  18. radius=radius,
  19. happy_threshold=threshold,
  20. seed=seed,
  21. )
  22. if minimal:
  23. sim = Minimal(model)
  24. else:
  25. sim = Simulator(model)
  26. sim.setTerminationTime(20.01)
  27. # sim.setVerbose(None)
  28. sim.simulate()
  29. setup = ("from Schelling import Schelling\n"
  30. "from benchmark_schelling import runthemodel")
  31. n_run = 100
  32. if __name__ == '__main__':
  33. parser = argparse.ArgumentParser()
  34. parser.add_argument("-M", "--minimal", action="store_true")
  35. args = parser.parse_args()
  36. framework = "PyPDEVS"
  37. if args.minimal:
  38. os.environ["PYPDEVS_MINIMAL"] = "1"
  39. framework = "PyPDEVS-Minimal"
  40. # import cProfile
  41. # import pstats
  42. # import io
  43. # start = timeit.default_timer()
  44. # pr = cProfile.Profile()
  45. # pr.enable()
  46. # runthemodel(42, 100, 8000, 2, 8, args.minimal)
  47. # pr.disable()
  48. # s = io.StringIO()
  49. # sortby = pstats.SortKey.TIME
  50. # ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
  51. # ps.print_stats()
  52. # print(s.getvalue())
  53. print(f"Running {framework} Schelling with 1000 agents in a 40x40 space, with a radius of one and a threshold of three.")
  54. tt = timeit.Timer(f'runthemodel(42, 40, 1000, 1, 3, {args.minimal})', setup=setup)
  55. a = tt.repeat(n_run, 1)
  56. median_time = sorted(a)[n_run // 2 + n_run % 2]
  57. print(f"{framework} Schelling-small Median Time for {n_run} runs (ms):", median_time * 1e3)
  58. #
  59. print(f"Running {framework} Schelling with 8000 agents in a 100x100 space, with a radius of two and a threshold of eight.")
  60. tt = timeit.Timer(f'runthemodel(42, 100, 8000, 2, 8, {args.minimal})', setup=setup)
  61. a = tt.repeat(n_run, 1)
  62. median_time = sorted(a)[n_run // 2 + n_run % 2]
  63. print(f"{framework} Schelling-large Median Time for {n_run} runs (ms):", median_time * 1e3)