询问仅含torch::Tensor类的libtorch头文件以加快编译速度
解决libtorch全量头文件编译耗时过长的问题
你可以通过包含libtorch提供的细分头文件替代全量的<torch/torch.h>,大幅缩短编译时间:
核心头文件说明
<torch/tensor.h>:仅包含torch::Tensor类的核心定义,是最基础的依赖<torch/creation.h>:包含torch::zeros、torch::ones等Tensor创建函数的声明<torch/io.h>:支持torch::Tensor向标准输出流(如std::cout)的输出操作
优化后的示例代码
#include <iostream> #include <torch/tensor.h> // 仅引入Tensor类定义 #include <torch/creation.h> // 引入Tensor创建函数 #include <torch/io.h> // 支持Tensor的流式输出 int main() { torch::Tensor t = torch::zeros({ 4, 5 }); std::cout << t << std::endl; return 0; }
- 额外编译加速建议
- 启用预编译头(PCH):将上述libtorch头文件添加到VS2022的预编译头中,仅需编译一次,后续编译复用结果
- 开启多进程编译:在项目属性中启用
/MP选项,利用多核CPU并行编译 - 保留增量编译:VS默认开启该功能,可减少重复编译的代码量
内容的提问来源于stack exchange,提问作者IronMan
相关产品推荐
相关产品推荐

