Search code examples
pythonpython-3.xloopsagent-based-modeling

How to run a command multiple times?


I am working on an agent-based model and I would like to run the following command 1,000 times:

model = MyModel()
for i in range(100):
    model.step()

I decided to use the while loop:

repetition = 0  
maxRepetition = 1000
while repetition <= maxRepetition: 
    model = MyModel()
    for i in range(100):
        model.step()    
    repetition += 1  

Nonetheless, it takes this loop a huge amount of time to conclude (more than 1 hour). Could anyone please recommend me a more efficient procedure?


Solution

  • If model.step() doesn't require iterational execution than there are libraries like threading, asyncio and multiprosessing for use.

    import multiprocessing
    
    def run_model(n):
        model = MyModel()
        for i in range(100):
            model.step
    
    with multiprocessing.Pool() as pool:
        pool.map(run_model, list(range(1000)))
    

    source: https://realpython.com/python-concurrency/