I am using the glm library, which is a header-only collection of math utilities intended for 3D graphics. By using -ftime-trace on Clang and ClangBuildAnalyzer, I've noticed that a lot of time is being spent instantiating glm types:
**** Templates that took longest to instantiate:
16872 ms: glm::vec<4, signed char, glm::packed_highp> (78 times, avg 216 ms)
15675 ms: glm::vec<4, unsigned char, glm::packed_highp> (78 times, avg 200 ms)
15578 ms: glm::vec<4, float, glm::packed_highp> (78 times, avg 199 ms)
... …Run Code Online (Sandbox Code Playgroud) 示例:说我在预编译的头文件中包括:
#include <vector>
Run Code Online (Sandbox Code Playgroud)
由于在我的项目中经常使用vector的一些实例,例如std :: vector,std :: vector等,因此,如果我在预编译标头中也将它们实例化,它将减少编译时间:
#include <vector>
template class std::vector<float>;
template class std::vector<int>;
Run Code Online (Sandbox Code Playgroud)
更进一步,将伪函数添加到使用一些函数的预编译头中是否有意义:
namespace pch_detail {
inline auto func() {
auto&& v = std::vector<float>{};
v.size();
v.begin();
v.front();
}
}
Run Code Online (Sandbox Code Playgroud)
我不确定翻译单元和模板如何真正工作,因此在我看来,如果我在预编译的标头中实例化它们,这意味着不必为每个.cpp文件都实例化它们。
更新资料
使用Visual Studio 2017和一些常用模板类的实例化在真实世界的代码库上进行了测试。
因此,至少就我而言,这花费了更多时间。