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

相关推荐
wj30558537810 小时前
课程 5:将官方 LTX-2.3 工作流改造成 GGUF 主模型工作流
python·cuda·comfyui
fpcc1 天前
并行编程实战——CUDA编程的打印输出
c++·cuda
(initial)4 天前
B-05. Unified Memory:Page Fault、Prefetch、Advise 的性能边
人工智能·cuda
ComputerInBook4 天前
C++ 关键字 constexpr 和 consteval 之注意事项
开发语言·c++·constexpr·consteval
zhoupenghui1687 天前
如何设置PyTorch程序在 GPU上运行
人工智能·pytorch·python·gru·cuda
weixin_377634847 天前
【CUDA版本冲突】Driver/library version mismatch
cuda
春夜喜雨11 天前
类型定义的使用差异using/typedef/define/constexpr
c++·typedef·using·constexpr·类型定义·define·常量声明
Hi2024021711 天前
CUDA-BEVFusion 开箱即用镜像使用指南
人工智能·自动驾驶·cuda·机器视觉
数据与后端架构提升之路14 天前
从 CUDA Kernel 到 TensorRT Plugin:一条 AI Infra 工程师的最小可复现路径
cuda编程·重写算子
fpcc14 天前
并行编程实战——异步编程的屏障的整体分析
人工智能·cuda