Created
April 23, 2016 18:23
-
-
Save drvinceknight/9242ec149030433b800ea1ba71411c89 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import json | |
| import time | |
| from multiprocess import Process, Queue | |
| import axelrod as axl | |
| def match_generator(players, turns=100, repetitions=1000): | |
| for rep in range(repetitions): | |
| for player1 in players: | |
| for player2 in players: | |
| players = (player1.clone(), player2.clone()) | |
| match = axl.Match(players, turns) | |
| yield match | |
| # Could probably just use `Process(target=func, args=(match, queue, repetitions))` | |
| class MatchProcess(Process): | |
| def __init__(self, match, queue): | |
| Process.__init__(self) | |
| self.match = match | |
| self.queue = queue | |
| def run(self): | |
| results = self.match.play() | |
| self.queue.put(results) | |
| class ProcessManager(object): | |
| def __init__(self, players, repetitions=100, max_processes=4, filename="results.out"): | |
| self.processes = [] | |
| self.max_processes = max_processes | |
| self.queue = Queue() | |
| self.file = open("filename", 'w') | |
| print("Building matches") | |
| self.matches = list(match_generator(players, repetitions=repetitions)) | |
| print("done") | |
| def clean_pool(self): | |
| terminated = [] | |
| for p in self.processes: | |
| # Look for naturally terminated processes. | |
| if not p.is_alive(): | |
| terminated.append(p) | |
| for t in terminated: | |
| self.processes.remove(t) | |
| def run(self): | |
| # Add workers | |
| while len(self.matches) > 0: | |
| while len(self.processes) < self.max_processes: | |
| p = MatchProcess(self.matches.pop(), self.queue) | |
| self.processes.append(p) | |
| p.start() | |
| # Clean Pool | |
| self.clean_pool() | |
| # Write Queue to disk | |
| # Could have another process just for this | |
| while self.queue.qsize() > 0: | |
| results = self.queue.get() | |
| self.file.write(json.dumps(results)) | |
| time.sleep(0.2) | |
| if __name__ == "__main__": | |
| players = [s() for s in axl.ordinary_strategies] | |
| p = ProcessManager(players) | |
| p.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment