You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用循环优化AGV车队节点调速代码以提升仿真速度?

优化AnyLogic Fleet节点进入速度设置代码及性能提升方案

问题背景

我在AnyLogic的Fleet属性「On enter node」中编写代码控制transporterFleet,当运输机进入特定节点时,通过对应agvCycle变量设置速度。但因为每个节点都要单独判断,写了一长串else-if代码,现在即使在「virtual」模式下仿真运行也很慢,怀疑是冗余代码导致。想知道怎么用循环实现,以及这样做能不能提升仿真速度?

原冗余代码

if (node == locationCycle1) {
    unit.setMaximumSpeed(agvSpeedCycle1/60.0, MPS);
}
else if (node == locationCycle2){
    unit.setMaximumSpeed(agvSpeedCycle2/60.0, MPS);
}
else if (node == locationCycle3){
    unit.setMaximumSpeed(agvSpeedCycle3/60.0,MPS);
}
else if (node == locationCycle4){
    unit.setMaximumSpeed(agvSpeedCycle4/60.0, MPS);
}
else if (node == locationCycle5){
    unit.setMaximumSpeed(agvSpeedCycle5/60.0, MPS);
}
else if (node == locationCycle6){
    unit.setMaximumSpeed(agvSpeedCycle6/60.0, MPS);
}
else if (node == locationCycle7){
    unit.setMaximumSpeed(agvSpeedCycle7/60.0, MPS);
}
else if (node == locationCycle8){
    unit.setMaximumSpeed(agvSpeedCycle8/60.0, MPS);
}
else if (node == locationCycle9){
    unit.setMaximumSpeed(agvSpeedCycle9/60.0, MPS);
}
else if (node == locationCycle10){
    unit.setMaximumSpeed(agvSpeedCycle10/60.0, MPS);
}

... // 持续到locationCycle27和agvSpeedCycle27

一、用循环/映射重构代码

方法1:数组配对遍历

  1. 在模型全局变量或Fleet专属变量中定义两个配对数组,分别存储节点和对应速度:
// 按顺序存储所有目标节点
Node[] cycleNodes = {locationCycle1, locationCycle2, ..., locationCycle27};
// 按对应顺序存储节点的目标速度
double[] cycleSpeeds = {agvSpeedCycle1, agvSpeedCycle2, ..., agvSpeedCycle27};
  1. 在「On enter node」事件中替换原else-if链为循环:
for (int i = 0; i < cycleNodes.length; i++) {
    if (node == cycleNodes[i]) {
        unit.setMaximumSpeed(cycleSpeeds[i] / 60.0, MPS);
        break; // 找到匹配节点后立即退出循环,避免多余判断
    }
}

方法2:HashMap键值对查找(性能最优)

  1. 在模型初始化事件(如Main的「On startup」)中创建节点-速度映射:
HashMap<Node, Double> nodeSpeedMap = new HashMap<>();
nodeSpeedMap.put(locationCycle1, agvSpeedCycle1);
nodeSpeedMap.put(locationCycle2, agvSpeedCycle2);
// ... 依次添加所有27组节点-速度配对
  1. 在「On enter node」事件中直接通过节点查找速度:
Double targetSpeed = nodeSpeedMap.get(node);
if (targetSpeed != null) {
    unit.setMaximumSpeed(targetSpeed / 60.0, MPS);
}

二、性能提升效果

原else-if链属于线性查找,每次进入节点最坏情况需要判断27次;改用数组循环后平均判断次数大幅减少,而HashMap的查找是O(1)时间复杂度(直接哈希定位),能将单次事件的执行时间降到最低。

当运输机数量多、节点访问频繁时,这种优化会明显提升仿真速度——即使在virtual模式下,减少冗余判断带来的CPU开销也能让仿真运行更流畅。同时重构后的代码更简洁,后续新增/修改节点速度时只需维护数组或映射,避免重复代码出错。

内容的提问来源于stack exchange,提问作者SimulationNewBe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 13:48:25