记录 | 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__

相关推荐
程序员小川10 小时前
Ubuntu22.04安装paddle
ai·cuda·paddle·cudnn
大鹅同志3 天前
在服务器上开Juypter Lab教程(远程访问)
运维·服务器·pytorch·jupyter·cuda·云服务器
一尺丈量4 天前
ffmpeg硬件解码一般流程
c++·人工智能·ffmpeg·cuda·硬件解码
Hi202402174 天前
RTX3060 FP64测试与猜想
性能优化·gpu·cuda·性能分析·gpgpu
Hi202402176 天前
smsp__inst_executed_pipe_fp64为什么对不上
性能优化·gpu·cuda·性能分析·gpgpu
杰克逊的日记7 天前
nvdia和cuda的区别与联系
cuda·nvdia
陈 洪 伟7 天前
虚拟内存、内存分段、分页、CUDA编程中的零拷贝
mmu·cuda·虚拟内存
山水阳泉曲13 天前
ffmpeg安装测试(支持cuda支持SRT)
ffmpeg·可用性测试·cuda·新版本·srt
hn_tzy16 天前
C++11中的constexpr
开发语言·c++·常量·constexpr·常量表达式
思绪无限21 天前
Ubuntu22.04安装深度学习的GPU环境详细教程(小白图文,显卡驱动、CUDA、cuDNN、PyTorch一步到位)
pytorch·深度学习·安装教程·cuda·ubuntu22·gpu环境配置·anaconda安装