I\'m replicating a small piece of Sugarscape agent simulation model in Python 3. I found the performance of my code is ~3 times slower than that of NetLogo. Is it likely the pro
This probably won't give dramatic speedups, but you should be aware that local variables are quite a bit faster in Python compared to accessing globals or attributes. So you could try assigning some values that are used in the inner loop into locals, like this:
def look_around(self):
max_sugar_point = self.point
max_sugar = self.world.sugar_map[self.point].level
min_range = 0
selfx = self.point[0]
selfy = self.point[1]
wlength = self.world.surface.length
wheight = self.world.surface.height
occupied = self.world.occupied
sugar_map = self.world.sugar_map
all_directions = self.all_directions
random.shuffle(all_directions)
for r in range(1, self.vision+1):
for dx,dy in all_directions:
p = ((selfx + r * dx) % wlength,
(selfy + r * dy) % wheight)
if occupied(p): # checks if p is in a lookup table (dict)
continue
if sugar_map[p].level > max_sugar:
max_sugar = sugar_map[p].level
max_sugar_point = p
if max_sugar_point is not self.point:
self.move(max_sugar_point)
Function calls in Python also have a relatively high overhead (compared to Java), so you can try to further optimize by replacing the occupied
function with a direct dictionary lookup.
You should also take a look at psyco. It's a just-in-time compiler for Python that can give dramatic speed improvements in some cases. However, it doesn't support Python 3.x yet, so you would need to use an older version of Python.