比如__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&gt;&gt;&gt;();
    cudaDeviceSynchronize();
    say_hello();
    return 0;
}
}

可以constexpr 来替代 __host__ __device,替代后的代码如下

#include <cstdio&gt;
#include <cuda_runtime.h&gt;

constexpr const char* cuthead(const char* p){
    return p+1;
}

__global__ void kernel(){
    printf(cuthead("Gello, world!n"));
}

int main(){
    kernel<<<1, 1&gt;&gt;&gt;();
    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__

原文地址:https://blog.csdn.net/weixin_42405819/article/details/134818476

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_45750.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注