效率澄清:询问一般乌龟类型的子集或询问品种?

时间:2017-07-25 16:14:34

标签: netlogo

我正在使用一个大型模型,每天都有许多代理执行许多程序。

做这样的事情会更好:

ask turtles [
 if type = "A" [do-A-thing]
 if type = "B" [do-B-thing]
]

或者

ask A-turtles [do-A-thing]
ask B-turtles [do-B-thing]

我希望降低计算量。

1 个答案:

答案 0 :(得分:2)

这是一个尝试两种方法的示例。它创造了100,000只海龟,并为每种情况执行1000次测试。方法2似乎更快。在我的机器上,方法1花了46.3秒,方法2花了30.6秒。在方法1中使用 ifelse 并没有多大帮助。方法2更快,因为你避免比较,这似乎是合乎逻辑的。

breed[A-turtles A-turtle]
breed[B-turtles B-turtle]

turtles-own [
 typ
]

; setup button callback function
to setup
  clear-all

  ; create turtles for approach 1
  create-turtles 100000
  ask turtles [
   ifelse (who < 50000) [
     set typ "A"
   ]
   [
     set typ "B"
   ]
  ]

 ; time approach 1
 let i 0
 let iter 1000
 reset-timer
 while [ i < iter ]
  [
    ; approach 1
    ask turtles [
      if typ = "A" [
        doSomething
      ]
      if typ = "B" [
        doSomething
      ]
    ]
    set i i + 1
  ]
  print (word "approach 1 time: " timer " secs")

  ; delete turtles, then create turtles for approach 2
  clear-all
  clear-turtles
  create-A-turtles 50000
  create-B-turtles 50000

  ; time approach 2
  set i 0
  reset-timer
  while [ i < iter ]
  [
    ; approach 2
    ask A-turtles [ doSomething ]
    ask B-turtles [ doSomething ]
    set i i + 1
  ]
  print (word "approach 2 time: " timer " secs")

end

to doSomething
  let i 0
  set i i + 1
  set i i - 1
end