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

相关推荐
李昊哲小课16 小时前
wsl ubuntu24.04 cuda13 cudnn9 pytorch 显卡加速
人工智能·pytorch·python·cuda·cudnn
wanzhong23332 天前
CUDA学习2-CPU和GPU的性能优化
深度学习·gpu·cuda·高性能计算
碧海潮生_CC8 天前
【CUDA笔记】01-入门简介
笔记·cuda
喆星时瑜11 天前
关于 ComfyUI 的 Windows 本地部署系统环境教程(详细讲解Windows 10/11、NVIDIA GPU、Python、PyTorch环境等)
python·cuda·comfyui
安全二次方security²14 天前
CUDA C++编程指南(1)——简介
nvidia·cuda·c/c++·device·cuda编程·architecture·compute unified
千年奇葩19 天前
Unity性能优化之:利用CUDA加速Unity实现大规模并行计算。从环境搭建到实战案例
c++·人工智能·unity·游戏引擎·cuda
ouliten19 天前
cuda编程笔记(34)-- 内存访问控制与缓存提示
笔记·cuda
ouliten20 天前
cuda编程笔记(33)--Thrust库的使用
笔记·cuda
安全二次方security²24 天前
CUDA-GDB(11)——调试示例演练
gdb·nvidia·cuda·调试·cuda-gdb·autostep·mpi cuda
SunkingYang25 天前
github上的secsgem源码有什么功能,如何基于现有源码secsgem开发一套既能做host又能做equipment的系统,应该如何设计
源码·host·secsgem·半导体协议·semi·equipment·如何设计