mesa
mesa copied to clipboard
Performance bottlenecks in mesa.discrete_space
Summary
While profiling mesa.discrete_space under a high-movement workload, I observed significant time spent in cell movement and occupancy checks. This issue summarizes the hotspots and proposes a few improvements.
Reproduction
import random
import cProfile
from mesa import Model
from mesa.discrete_space.grid import OrthogonalVonNeumannGrid
from mesa.discrete_space.cell_agent import CellAgent
class DummyModel(Model):
pass
def run_benchmark():
model = DummyModel()
grid = OrthogonalVonNeumannGrid((100, 100), capacity=1)
agents = [CellAgent(model) for _ in range(5000)]
# initial placement
for agent in agents:
agent.cell = grid.select_random_empty_cell()
# random movement loop
for _ in range(500):
for agent in agents:
neighbors = agent.cell.neighborhood
target = random.choice(list(neighbors))
if target.is_empty:
agent.cell = target
if __name__ == "__main__":
cProfile.run("run_benchmark()", sort="cumtime")
Observations
Cell.is_emptyis called very frequently and currently computeslen(self._agents) == 0every time.CellAgent.celltriggers add or remove operations that account for a large portion of total runtime.- Neighborhood access wraps results in
CellCollectionand constructs intermediate mappings, contributing additional allocation overhead.
Total runtime is around 63 seconds
CellAgent.cell ~14.7s
Cell.is_empty ~11.1s
Cell.neighborhood ~6.8s
Cell.remove_agent ~6.1s
Cell.add_agent ~4.8s
Proposed Improvements
- Make
_emptythe single source of truth for emptiness and avoid recomputinglen(self._agents)on everyis_emptycall. - Reduce overhead in the movement pathnto avoid unnecessary repeated checks and work.
- Simplify how neighborhoods are constructed and returned to reduce intermediate allocations during frequent movement.
I plan to address these in separate PRs to keep changes focused and measurable.