C++ 运行时效率
C++ Run time efficiency
我正在用节点创建一个十六进制板。我在这段代码中的所有内容都可以完美运行。我的问题是加星号的项目减慢了这个循环的速度,从 ~1 秒到大约 1 分钟。这不是矢量中的项目数,因为如果我将它们全部删除,除了最后一个,它仍然需要~1分钟。无论哪种方式,都没有运行时错误。
for (x = 0; x < size; ++x)
{
for (y = 0; y < size; ++y)
{
this->nodes[x][y].neighbors = std::vector<node>(6);
if ((x == 0) && (y == 0))
{
this->nodes[x][y].neighbors =
{
nodes[x + 1][y],
this->nodes[x][y + 1]
};
}
else if ((x == 0) && (y == max))
{
this->nodes[x][y].neighbors =
{
this->nodes[x + 1][y],
this->nodes[x][y - 1],
this->nodes[x + 1][y - 1]
};
}
else if ((x == max) && (y == 0))
{
this->nodes[x][y].neighbors =
{
this->nodes[x - 1][y],
this->nodes[x][y + 1],
this->nodes[x - 1][y + 1]
};
}
else if ((x == max) && (y == max))
{
this->nodes[x][y].neighbors =
{
this->nodes[x - 1][y],
this->nodes[x][y - 1]
};
}
else if (y == 0 && (x != 0 && x != max))
{
this->nodes[x][y].neighbors =
{
this->nodes[x - 1][y],
this->nodes[x + 1][y],
this->nodes[x - 1][y + 1],
this->nodes[x][y + 1]
};
}
else if (y == max && (x != 0 && x != max))
{
this->nodes[x][y].neighbors =
{
this->nodes[x - 1][y],
this->nodes[x + 1][y],
this->nodes[x - 1][y - 1],
this->nodes[x][y - 1]
};
}
else if (x == 0 && (y != 0 && y != max))
{
this->nodes[x][y].neighbors =
{
this->nodes[x][y - 1],
this->nodes[x][y + 1],
this->nodes[x + 1][y],
this->nodes[x + 1][y - 1]
};
}
else if (x == max && (y != 0 && y != max))
{
this->nodes[x][y].neighbors =
{
this->nodes[x][y - 1],
this->nodes[x][y + 1],
this->nodes[x - 1][y - 1],
this->nodes[x - 1][y]
};
}
else
{
this->nodes[x][y].neighbors =
{
this->nodes[x + 1][y],
this->nodes[x - 1][y],
this->nodes[x][y - 1],
this->nodes[x + 1][y - 1],
this->nodes[x][y + 1],
this->nodes[x - 1][y + 1]
};
}
}
}
鉴于这个想法是跟踪您知道已预先创建的邻居,您可能只想保留指向它们的引用或指针; 您不应该像当前那样按值复制node
。
您可以使用 vector<reference_wrapper<node>>
或 vector<node*>
,并像这样进行相应的初始化:
nodes[x][y].neighbors = { ref(nodes[a][b]), ref(nodes[c][d])... };
nodes[x][y].neighbors = { &nodes[a][b], &nodes[c][d], ... };
使用指针,当您访问neighbors[n]
时,显然也需要取消引用指针。
关于为什么这么慢...按价值复制意味着将node
抄入neighbours
就是复制所有那些相邻的node
邻居,以及他们的邻居,令人作呕......随着具有长邻居层次结构的节点数量的增加,速度越来越慢。
缓慢来自两件事:
- 最后一个 else 条款受到的打击最大。
- 最后一个子句复制的节点项比其他子句多
几点建议:
- 使用指针或索引,而不是为邻居
node
对象。减少复制。 - 为邻居使用固定大小的数组会更快。将显着改善局部性和记忆力。您必须为该数组添加邻居计数。
相关文章:
- CMake-按正确顺序将项目与C运行时对象文件链接
- 我在c++代码中生成了一个运行时#3异常
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 删除指向指针的指针是运行时错误吗
- 如何用参数值调用函数(仅在运行时已知)
- 为什么即使使用-cudart-static进行编译,库用户仍然需要链接到cuda运行时
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- c++中的指针和运行时错误
- 在运行时处理类型擦除的数据-如何不重新发明轮子
- 有没有一种方法可以测量c++程序的运行时内存使用情况
- 建议在运行时将带有类实例的列表从c++导入qml
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 如何在GTK程序运行时禁用屏幕保护程序/电源管理/屏幕消隐
- 在同一模拟中使用静脉和静脉_ inet内容时出现运行时错误
- 读取文件时运行时的未知行为
- 函数在Windows或Linux上运行时表现不同
- 在声明中合并两个常量"std::set"(不是在运行时)
- 正确答案,但在效率阶段出现运行时错误
- C++ 运行时效率
- 如何找到一个运行时效率的c++代码