c++ - 为什么这段代码运行这么慢?

标签 c++ optimization profiling

我被这段代码严重难住了,我运行了 gprof 并发现该程序在 contains() 函数中花费了 40% 的时间,该函数运行了大约 8000 次。该程序本身总共需要 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 倍,因为它是缓存友好的。 vector push_back 具有 O(1) 摊销难度,就像列表一样。无论如何, vector 对于中间插入是不利的。 还有 std::mapstd::unordered_map专为快速搜索而设计。

关于c++ - 为什么这段代码运行这么慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20941140/

相关文章:

python - 带有智能指针的 Swig 类型图

c++ - 使用 QWT 和 Microsoft Visual C++ 2010 绘制 MatLab 等效图

c++ - 帮助 map C++

Java表达式优化

sql - 优化查询以删除 "Using where; Using temporary; Using filesort"

c++ - OpenMP:ON NUMA 的 pragma cancel

c++ - 优化正在取消我在 clang 6 中的整数溢出检查

profiling - 有 Go 分析器吗?

c++ - CUDA 测量 2 个 _syncthread() 点之间的时间

c++ - 不稳定的分析时间