我正在用Python 3复制Sugarscape代理模拟模型的一小部分。 我发现我的代码性能比NetLogo慢约3倍。 这可能是我的代码问题,还是Python本身的固有限制?显然,这只是代码的一部分,但这正是Python花费运行时间三分之二的地方。 我希望如果我写了一些非常低效的东西,它可能会在这个片段中显示出来:
在我的计算机上,Python代码运行1000步需要15.5秒;在同一台笔记本电脑上,Java内嵌于浏览器中的NetLogo模拟可以在不到6秒内完成1000步。
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步。
编辑:刚刚检查了使用Java实现的Repast。它也大约与NetLogo相同,为5.4秒。 最近的比较 Java和Python之间没有优势,所以我想这只是我的代码有问题吧?
编辑:我明白MASON应该比Repast还要快,但最终仍然运行Java。
occupied
函数时,时间进一步降至10.4秒。 - max