为什么这段代码运行这么慢
Why is this code running so slowly?
我被这段代码严重难倒了,我运行了gprof,发现该程序在运行约8000次的contains()函数中花费了40%的时间。 程序本身总共需要 15 秒才能运行。有谁知道为什么需要这么长时间,或者可能是什么?
// Check a list to see if it contains a tile object at x,y
bool contains(std::list<struct Tile>* list, int x, int y){
std::list<struct Tile>::iterator it;
for(it = list->begin(); it != list->end(); it++){
if((*it).x == x && (*it).y == y){
return true;
}
}
return false;
}
使用std::vector
,由于它是缓存友好的,因此遍历速度大约快 100 倍。向量push_back具有 O(1) 摊销难度,就像列表一样。无论如何,向量对中间插入不利。此外,std::map
和std::unordered_map
专为快速搜索而设计。
相关文章:
- 任何人都可以弄清楚这段代码如何显示运行错误?它打印无限时间 -1 以及正确答案
- 这段代码在获得错误输入时不会阻止 stoi 运行
- 通过创建单个线程来运行一段代码可加快执行速度
- 这段代码可编译,但在visualstudio2015社区中运行(c++)时不显示输出
- 为什么矢量上的这段代码会给出运行时错误
- 为什么这段代码会产生运行时错误
- 为什么这段代码不能正常工作???我的意思是,为什么当我运行它时它没有显示任何内容?
- 为什么这段代码会出现运行时分段错误
- 我可以/应该在 GPU 上运行统计应用程序的这段代码吗?
- 为什么这段代码不能运行?[初级]
- 为什么这段代码运行这么慢
- 为什么这段代码在Mac和Red Hat中的运行方式如此不同
- C++:如果输入不是整数,为什么这段代码会运行一个无休止的循环
- 调试使用调试标志运行的代码,并使用 opt 标志运行段错误
- 不理解这段代码(它无条件运行)
- 为什么这段代码不能用 clang 构建,用 gcc 崩溃,但在 VC++ 上运行良好?
- 为什么尽管我声明了一个不完整类型的自动实例,但这段代码还是编译并运行
- 这段代码是如何运行的
- 如何运行这段c++代码
- 如何在纸上运行这段代码