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

相关推荐
weiwei228443 天前
NVIDIA Kernel级性能分析工具Nsight Compute入门详解
gpu·cuda·nsight compute
意法半导体STM326 天前
STM32 USBx Device MSC standalone 移植示例 LAT1488
单片机·嵌入式硬件·device·msc·standalone·usbx
山烛12 天前
深度学习:CUDA、PyTorch下载安装
人工智能·pytorch·python·深度学习·cuda
伊织code13 天前
PyTorch API 2
pytorch·api·cpu·cuda·微分·autograd
探模之翼15 天前
利用 Windows GPU 在 WSL2 中安装并配置 CUDA Toolkit
cuda·wsl2
weiwei2284415 天前
NVIDIA系统级性能分析工具Nsight Systems入门详解
gpu·cuda·nsight systems
charlee4421 天前
在本地部署Qwen大语言模型全过程总结
大模型·cuda·qwen·量化
weiwei2284422 天前
CUDA编程初探
gpu·cuda
www.021 个月前
在ubuntu服务器下安装cuda和cudnn(笔记)
linux·ubuntu·cuda·cudnn·服务器环境
ouliten1 个月前
cuda编程笔记(13)--使用CUB库实现基本功能
笔记·cuda