记录 | CUDA编程中用constexpr替代__host__&__device__

比如用 __host__ & __device__ 的情况如下:

复制代码
#include <cstdio>
#include <cuda_runtime.h>

__host__ __device__ void say_hello(){
    printf("Hello, world!\n");
}

__global__ void kernel(){
    say_hello();
}

int main(){
    kernel<<<1, 1>>>();
    cudaDeviceSynchronize();
    say_hello();
    return 0;
}
}

则可以用 constexpr 来替代 __host__ __device,替代后的代码如下:

复制代码
#include <cstdio>
#include <cuda_runtime.h>

constexpr const char* cuthead(const char* p){
    return p+1;
}

__global__ void kernel(){
    printf(cuthead("Gello, world!\n"));
}

int main(){
    kernel<<<1, 1>>>();
    cudaDeviceSynchronize();
    printf(cuthead("Cello, world!\n"));
    return 0;
}

● 这样相当于把 constexpr 函数自动变成修饰符 __host__ __device__ ,从而两边都可以调用;

● 因为 constexpr 通常都是一些可以内联的函数,数学计算表达式之类的,一个个加上太累了,所以产生了这个需求;

● 不过必须指定 --expt-relaxed-constexpr 这个选项才能用这个特性,咱们可以用 CMake 的生成器表达式来实现只对 .cu 文件开启此选项 (不然给到 gcc 就出错了);

复制代码
# 这个.cu用nvcc编译就是这样的 
nvcc demo.cu --expt-relaxed-constexpr

● constexpr里面没办法调用 printf,也不能用 __syncthreads 之类的 GPU 特有的函数,因此也不能完全替代 __host____device__

相关推荐
封奚泽优3 天前
使用mmdetection项目进行训练记录
pytorch·python·cuda·mmdetection·mmcv
fpcc4 天前
并行编程实战——CUDA编程的其它Warp函数
c++·cuda
Autumn72995 天前
【系统重装】PYTHON 入门——速通版
开发语言·python·conda·cuda
fpcc6 天前
并行编程实战——CUDA编程的Warp Vote
c++·cuda
fpcc6 天前
并行编程实战——CUDA编程的Warp Shuffle
c++·cuda
风流倜傥唐伯虎7 天前
N卡深度学习环境配置
人工智能·深度学习·cuda
fpcc8 天前
并行编程实战——CUDA编程的Enhancing Memory Allocation
c++·cuda
fpcc9 天前
AI和大模型之一介绍
人工智能·cuda
闪电橘子9 天前
Pycharm运行程序报错 Process finished with exit code -1066598273 (0xC06D007F)
ide·python·pycharm·cuda
fpcc10 天前
并行编程实战——CUDA编程的内存建议
c++·cuda