为什么这段代码运行这么慢

Why is this code running so slowly?

本文关键字:运行 段代码 为什么 代码      更新时间:2023-10-16

我被这段代码严重难倒了,我运行了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::mapstd::unordered_map专为快速搜索而设计。