c++ - 如果使用预定义的 map ,重建项目需要非常长的时间?

标签 c++ visual-studio visual-c++

编译/链接设置相当正常(/O2 用于优化,/LTCG 用于链接器 - 这是由于使用使用/GL 编译的模块而强制执行的)。

我找到了导致编译时间增加的代码段,但我不知道如何解决这个问题。尽管编译时间很长,但当前代码在最终完成时确实可以正常工作。

当删除以下函数后,编译时间从 125 秒减少到 4 秒(几乎所有的时间增益都在链接阶段):

static void InitializeItemSlotLists(std::map<uint32_t, uint32_t>& HEAD_IDS, std::map<uint32_t, uint32_t>& SHOULDER_IDS, std::map<uint32_t, uint32_t>& CHEST_IDS, std::map<uint32_t, uint32_t>& GLOVE_IDS, std::map<uint32_t, uint32_t>& WAIST_IDS, std::map<uint32_t, uint32_t>& LEGS_IDS, std::map<uint32_t, uint32_t>& FEET_IDS, std::map<uint32_t, uint32_t>& WEAPON_1H_IDS, std::map<uint32_t, uint32_t>& WEAPON_2H_IDS, std::map<uint32_t, uint32_t>& SHIELD_IDS, std::map<uint32_t, uint32_t>& OFFHAND_IDS) {
    HEAD_IDS[60202] = 93792;
    HEAD_IDS[60222] = 35113;
    HEAD_IDS[60237] = 81960;
    HEAD_IDS[60243] = 77144;
    HEAD_IDS[60249] = 91486;
    HEAD_IDS[60256] = 91255;
    HEAD_IDS[60258] = 82002;
    HEAD_IDS[60299] = 82025;
    (This continues for 5000 or so more lines.)
}

我可以在运行时从外部文本文件加载所有这些,但老实说,这只会增加毫无意义的复杂性。尽管数据看起来多么随意,但它在未来极不可能发生变化。

问题是它试图优化这个巨大的数据 block 吗?如果是这样,有没有一种方法可以强制它忽略这个特定文件以进行优化(它在自己的 .cpp 文件中,有自己的头文件来预定义函数)?

最佳答案

如果您必须使用静态数据执行此操作,并且您不想/不能使用 C++11 提供的映射大括号初始化器,那么避免编译器尝试优化性能受到影响的方法5000 行 std::map 赋值是将所有数据以某种方式放入静态数组中,如下所示:

#include <map>
#include <stdint.h>

typedef std::map<uint32_t, uint32_t> IdMap;

struct IdRow {
  uint32_t src;
  uint32_t dst;
};

IdRow InitialHeadIds[] = {
  { 60202, 93792 },
  { 60222, 35113 },
  { 60237, 81960 },
  { 60243, 77144 },
  { 60249, 91486 },
  { 60256, 91255 },
  { 60258, 82002 },
  { 60299, 82025 }
};

static void InitializeItemSlotLists(
    IdMap& HEAD_IDS, IdMap& SHOULDER_IDS, IdMap& CHEST_IDS, IdMap& GLOVE_IDS,
    IdMap& WAIST_IDS, IdMap& LEGS_IDS, IdMap& FEET_IDS, IdMap& WEAPON_1H_IDS,
    IdMap& WEAPON_2H_IDS, IdMap& SHIELD_IDS, IdMap& OFFHAND_IDS) {
  for (int i = 0; i < sizeof(InitialHeadIds) / sizeof(IdRow); i++) {
    IdRow curr = InitialHeadIds[i];
    HEAD_IDS[curr.src] = curr.dst;
  }
}

int main() {
  IdMap headIds, otherIds;
  InitializeItemSlotLists(
    headIds, otherIds, otherIds, otherIds, otherIds, otherIds, otherIds,
    otherIds, otherIds, otherIds, otherIds);
  return 0;
}

关于c++ - 如果使用预定义的 map ,重建项目需要非常长的时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25336521/

相关文章:

c++ - 部分模板特化错误

asp.net - 组织 Web 应用程序

c++ - 如何在Visual Studio中包括OpenSSL

visual-c++ - 从特征库检查向量/矩阵中的变量

visual-c++ - 在 C++/CLI 中,帽子字符 ^ 有何作用?

c++ - 转义特殊字符

c++ - C++中的字符串 View

c++ - 阻塞读和非阻塞读有什么区别?

c# - Visual Studio 解决方案找不到System.Web.Http.WebHost

c++ - 如何在 C++ 的 MFC 窗体中访问全局变量