我需要在同一个补丁中为所有受某些属性约束的海龟计算最近邻龟。我写的代码花了很多时间,我想知道是否有任何其他方法来优化它。我在turtle中定义了一个属性 neighbor 来存储最近的邻居。
to set_neighbor
ask patches [
ask turtles-here with [ life_stage = "STAGE1" ] [
set neighbor min-one-of other turtles-here with [ life_stage != "STAGE2" ] [ (distance myself) ]
]
]
end
我尝试通过进行以下更改来优化代码,但最终花费了更多时间。我假设如果我将查询的结果存储在变量中并且稍后多次使用该变量,那么它将比多次执行查询本身更快。
to set_neighbor
ask patches [
let turt_temp turtles-here with [ life_stage != "STAGE2" ]
ask turtles-here with [ life_stage = "STAGE1" ] [
set neighbor min-one-of other turt_temp [ (distance myself) ]
]
]
end
我真的很感激任何指针。提前谢谢。
答案 0 :(得分:2)
为什么补丁会问海龟呢?这应该做同样的事情,但速度要快一些,特别是如果你在STAGE1
有很多没有海龟的补丁:
to set_neighbor
ask turtles with [ life_stage = "STAGE1" ] [
set neighbor min-one-of other turtles-here with [ life_stage != "STAGE2" ] [ (distance myself) ]
]
end
我不确定只是为什么你的第二次实施速度较慢。如果你在STAGE1
有很多没有任何海龟的补丁(特别是如果它们上面还有很多其他的乌龟),我可以看到它变慢了。
答案 1 :(得分:0)
另一种选择(我不能告诉哪些更快)是通过仅在同一补丁上同时存在stage1和not(stage2)海龟的情况下限制请求的数量。我还使用with-min
代替min-one-of
,但我再也不知道哪个更快。
to set_neighbor
ask patches with [ any? turtles with [ life_stage = "STAGE1" ] and any? turtles with [ life_stage != "STAGE2" ] ]
[ ask turtles-here with [ life_stage = "STAGE1" ]
[ set neighbor other turtles-here with [ life_stage != "STAGE2" ] with-min [ distance myself ]
]
]
end