我正在 Python 3 中复制一小部分 Sugarscape 代理模拟模型。我发现我的代码性能比 NetLogo 慢约 3 倍。这可能是我的代码的问题,还是 Python 的固有限制?
显然,这只是代码的一部分,但这正是 Python 花费了三分之二的运行时间的地方。我希望如果我写了一些非常低效的东西,它可能会出现在这个片段中:
UP = (0, -1)
RIGHT = (1, 0)
DOWN = (0, 1)
LEFT = (-1, 0)
all_directions = [UP, DOWN, RIGHT, LEFT]
# point is just a tuple (x, y)
def look_around(self):
max_sugar_point = self.point
max_sugar = self.world.sugar_map[self.point].level
min_range = 0
random.shuffle(self.all_directions)
for r in range(1, self.vision+1):
for d in self.all_directions:
p = ((self.point[0] + r * d[0]) % self.world.surface.length,
(self.point[1] + r * d[1]) % self.world.surface.height)
if self.world.occupied(p): # checks if p is in a lookup table (dict)
continue
if self.world.sugar_map[p].level > max_sugar:
max_sugar = self.world.sugar_map[p].level
max_sugar_point = p
if max_sugar_point is not self.point:
self.move(max_sugar_point)
NetLogo 中大致等价的代码(这个片段比上面的 Python 函数做得更多):
; -- The SugarScape growth and motion procedures. --
to M ; Motion rule (page 25)
locals [ps p v d]
set ps (patches at-points neighborhood) with [count turtles-here = 0]
if (count ps > 0) [
set v psugar-of max-one-of ps [psugar] ; v is max sugar w/in vision
set ps ps with [psugar = v] ; ps is legal sites w/ v sugar
set d distance min-one-of ps [distance myself] ; d is min dist from me to ps agents
set p random-one-of ps with [distance myself = d] ; p is one of the min dist patches
if (psugar >= v and includeMyPatch?) [set p patch-here]
setxy pxcor-of p pycor-of p ; jump to p
set sugar sugar + psugar-of p ; consume its sugar
ask p [setpsugar 0] ; .. setting its sugar to 0
]
set sugar sugar - metabolism ; eat sugar (metabolism)
set age age + 1
end
在我的电脑上,Python 代码运行 1000 步需要 15.5 秒;在同一台笔记本电脑上,在浏览器中以 Java 运行的 NetLogo 模拟在不到 6 秒的时间内完成了 1000 步。
编辑:刚刚检查了 Repast,使用 Java 实现。它也与 5.4 秒的 NetLogo 大致相同。最近Java 和 Python 之间的比较表明 Java 没有优势,所以我想这应该归咎于我的代码?
编辑:我知道MASON应该比 Repast 更快,但它最终仍然运行 Java。