CUDA template kernel 与其他编译器合作编译
2016-12-11 20:58
211 查看
简介
在优化Kernel的时候,希望某些变量是常量,例如循环的次数相关的变量。如果次数限制是常量的话,编译器就可以将循环展开。展开的循环,会省掉一些判断,从而节省一些计算时间。C++的模版中可以使用常量。但是我又不想所有的源代码都由
nvcc来编译(其实C++的代码还是调用的host compiler),故此,我写这篇博客来提供一种方法。
代码实例
实例中有三个文件:main.cpp用host compiler来编译。
cuda_interfaces.cu用
nvcc来编译。
cuda_interfaces.h是
cuda_interfaces.cu的接口头文件。
// main.cpp #include <iostream> #include "cuda_interfaces.h" int main(int argc, char** argv){ su::gpu_func<0>(); su::gpu_func<1>(); su::gpu_func<2>(); su::gpu_func<3>(); su::gpu_func<4>(); su::gpu_func<5>(); return EXIT_SUCCESS; }
// cuda_interfaces.h #ifndef __CUDA_INTERFACES_H__ #define __CUDA_INTERFACES_H__ namespace su{ template<int _s> void gpu_func(); } #endif
// cuda_interfaces.cu #include <host_defines.h> #include <device_launch_parameters.h> #include <iostream> using namespace std; namespace su{ template <int _s> __global__ void kernel_func(int *data) { int x = threadIdx.x + blockIdx.x*blockDim.x; if (x < _s){ data[x] = _s; } else{ data[x] = 0; } } template<int _s> void gpu_func() { int n_threads = 32; int *h_data = new int[n_threads]; int *d_data = NULL; cudaMalloc(&d_data, n_threads*sizeof(int)); kernel_func<_s><<<1, n_threads>>>(d_data); cudaMemcpy(h_data, d_data, n_threads*sizeof(int), cudaMemcpyDeviceToHost); for (int i = 0; i < n_threads; i++){ cout << h_data[i] << " "; } cout << endl; // release memory delete[] h_data; h_data = NULL; cudaFree(d_data); d_data = NULL; } // note _s only support 0,1,2,3,4,5 template void gpu_func<0>(); template void gpu_func<1>(); template void gpu_func<2>(); template void gpu_func<3>(); template void gpu_func<4>(); template void gpu_func<5>(); }
上述代码执行结果如下:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 3 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 4 4 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 5 5 5 5 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
关键点
完成在模版中使用常量的关键在于在.cu文件里的声明,告诉nvcc要编译哪几个常量的函数!
Enjoy!
相关文章推荐
- ubuntu 12.04 64bit上使用32bit编译器编译kernel
- CUDA程序编译过程中产生警告的解决方法
- kernel编译
- Android I9100 源码编译 Step.3----安装JDK编译器
- gcc编译器实验---对gcc编译参数的详细说明
- ubuntu16.04+cuda8.0+cudnn5.1+caffe------caffe安装与编译
- 32位window7的CUDA编译环境配置
- 如何解决cuda 5.0 编译dynamic parallelism 功能代码时的 fatal error
- 【神经网络与深度学习】【CUDA开发】服务器(多GPU)caffe安装和编译
- 在C++程序中调用被C编译器编译后的函数为什么要加extern “C”
- 如何查看一个class文件,是jdk什么版本的编译器编译的?
- 抽取VS文件组成类GCC的编译器,并编译C程序为dll动态链接库
- vs2008 中,在编译Tcl扩展库时调用其他的动态库 (动态库调用动态库)
- 在Windows 下使用CodeBlocks 自带编译器实现对编译的优化
- CUDA8.0+OpenCV2.4.13+VS2015+Win10+TBB混合编译
- 编译全攻略-编译器处理及LNK错误的解决方法(2)
- 通过Daffodil for VS使VS2010的IDE可以用VC6 VC7.1 VC9等编译器进行项目编译
- 华天正的开发板 如何单独编译kernel
- 在君正M200平台android编译系统中集成kernel
- 新手玩Linux 之 u-boot和kernel的编译和下载