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

相关推荐
梦想不只是梦与想6 天前
PyTorch、CPU、GPU、CUDA
人工智能·pytorch·python·深度学习·机器学习·cuda
Blockbuater_drug7 天前
OpenMM分子动力学模拟02 安装:Linux:conda 一条命令装通 GPU 加速的分子模拟环境
linux·conda·cuda·gpu驱动·pythonpath·openmm安装
椒颜皮皮虾྅8 天前
让文档不止于文字:DeploySharp + PP-Structure,打通版面分析与表格重建
开发语言·学习·c#·.net·cuda
椒颜皮皮虾྅10 天前
模型部署不再卡在环境上:DeploySharp 四大推理引擎与 Windows/Linux 离线交付实战
linux·运维·开发语言·人工智能·windows·计算机视觉·cuda
椒颜皮皮虾྅10 天前
让 C# 读懂整张图:DeploySharp 驱动 PaddleOCR v4/v5/v6,打通 OCR 全流程
开发语言·人工智能·深度学习·学习·c#·ocr·cuda
fpcc16 天前
并行编程实战—CUDA中的Tile编程之八优化提示
cuda·1024程序员节·并行编程
本地化文档17 天前
cutile-rs-book-l10n
rust·gpu·nvidia·cuda·sphinx·crowdin
Web3&Basketball18 天前
TorchTPU 迁移实战:3 个 CUDA 卡点
pytorch·性能调优·cuda·tpu·模型迁移·torchtpu
燃烧的枫21 天前
Windows 下 YOLO26 的 TensorRT C++ 部署
人工智能·pytorch·windows·计算机视觉·tensorrt·cuda·yolo26