在预编译头文件中实例化模板会减少编译时间吗?

Vik*_*ehr 5 c++ precompiled-headers compile-time translation-unit

示例:说我在预编译的头文件中包括:

#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和一些常用模板类的实例化在真实世界的代码库上进行了测试。

  1. 实例化通用模板类:71731 ms
  2. 无实例:68544 ms

因此,至少就我而言,这花费了更多时间。

Bat*_*eba 6

是的,它可以有所作为。

然后,翻译单元中的实例化可以利用预编译头中的数据,并且编译器可以比 C++ 标准库头更快地读取该数据。

但是您必须维护实例化列表,因此这种编译时优化可能会带来更多麻烦,而不是其价值 - 如果您有不再需要的实例化,您的想法可能最终会产生相反的效果。


fgh*_*ghj 5

有趣的是,但至少对于clang(4.0.1)你的变体增加了编译时间:

1. no pch

real    0m0,361s
user    0m0,340s
sys     0m0,021s

2. pch, no explicit instantiate

real    0m0,297s
user    0m0,280s
sys     0m0,017s

3. pch, explicit instantiate

real    0m0,507s
user    0m0,474s
sys     0m0,033s
Run Code Online (Sandbox Code Playgroud)

我使用这样的代码:

#include <iostream>
#include "test.h"

int main() {
        std::vector<float> a = {1., 2., 3.};
        for (auto &&e : a) {
                std::cout << e << "\n";
        }
        std::vector<int> b = {1, 2, 3};
        for (auto &&e : b) {
                std::cout << e << "\n";
        }
}
Run Code Online (Sandbox Code Playgroud)

案例2测试.h

#pragma once

#include <vector>
Run Code Online (Sandbox Code Playgroud)

案例3

#pragma once

#include <vector>
template class std::vector<float>;
template class std::vector<int>;
Run Code Online (Sandbox Code Playgroud)

以及这样的编译脚本:

echo "no pch"
time clang++ -std=c++11 main.cpp

echo "pch, no explicit instantiate"
clang++ -std=c++11 -x c++-header test.h -o test.pch
time clang++ -std=c++11 -include-pch  test.pch main.cpp 

echo "pch, explicit instantiate"
clang++ -std=c++11 -x c++-header test2.h -o test2.pch
time clang++ -std=c++11 -include-pch  test2.pch main2.cpp 
Run Code Online (Sandbox Code Playgroud)