0

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?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • 1
    What this code intend to do ? Depends on that if the code inside a loop can be run concurently or not. – qocu Nov 02 '20 at 23:37
  • 1
    We dont know what `step()` does, but sure, running a function 100,000 times sequentally will be slow. You could instead start 1000 independent threads – OneCricketeer Nov 02 '20 at 23:38
  • ABMs often run on a grid, say 100x100 - that is you need to update 10,000 cells 100 times, 1000 times... this takes time! If your program is working, I suggest you post a request for help on codereview.stackexchange, this is probably a better place for this sort of questions. – Reblochon Masque Nov 02 '20 at 23:45
  • @ReblochonMasque when suggesting users post on CR it would be great if there was also a suggestion like "_Please read the relevant help center pages like '[What topics can I ask about here?](https://codereview.stackexchange.com/help/on-topic)' and '[How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask)_". In the current form the code above would likely be closed as off-topic because it is missing context, which happens all to often. – Sᴀᴍ Onᴇᴌᴀ Nov 02 '20 at 23:49
  • The "step( )" function makes the agents perform their respective functions for 1 cycle. There are 5 agents sequentially executing functions in the model. The code is really big, that's why I only put the last part, but I forgot to explain "step( )" – Luiz Filippe Santana Adão Nov 02 '20 at 23:49
  • 1
    haha, you get your share of bad questions on CR too. Of course, I envisioned a great question, with all the relevant code and details, but I will keep your suggestion in mind @SᴀᴍOnᴇᴌᴀ, because that was a silent, and ambitious assumption; thank you! – Reblochon Masque Nov 03 '20 at 01:13

1 Answers1

1

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/

qocu
  • 385
  • 4
  • 13