CUDA小测试之sign函数

sign(x)函数:对参数x取符号并归一,返回-1,0,1

看到很多c++库使用三元运算符实现,想看看在cuda中的表现

测试:

__global__ void test0() {
    const int idx = blockIdx.x*blockDim.x +threadIdx.x;
    float x = hash_uniform(idx) - 0.5f;
    float b = x; //参考
}
__global__ void test1() {
    const int idx = blockIdx.x * blockDim.x + threadIdx.x;
    float x = hash_uniform(idx) - 0.5f;
    float b = (x < 0.0f) ? -1.0f : (x > 0.0f) ? 1.0f : 0.0f;  //C程序一般使用 直观
}
__global__ void test2() {
    const int idx = blockIdx.x * blockDim.x + threadIdx.x;
    float x = hash_uniform(idx) - 0.5f;
    float b = -(x < 0.f) + (x > 0.f);//优化分支
}
__global__ void test3() {
    const int idx = blockIdx.x * blockDim.x + threadIdx.x;
    float x = hash_uniform(idx) - 0.5f;
    float b = glm::sign(x); //glm数学库
}

结果:

/*
 dim3 block = {1<<10 ,1,1 };
 dim3 thread = {1024 ,1,1 };
t0用时:0.0578ms
t1用时:0.4581ms
t2用时:0.2723ms
t3用时:1.2843ms

t0用时:0.0601ms
t1用时:0.5414ms
t2用时:0.221ms
t3用时:1.145ms

dim3 block = {1<<20 ,1,1 };
dim3 thread = {1024 ,1,1 };
t0用时:21.9258ms
t1用时:30.8275ms
t2用时:26.1951ms
t3用时:922.669ms

t0用时:21.7413ms
t1用时:31.192ms
t2用时:25.5955ms
t3用时:925.672ms

dim3 block = {1<<25 ,1,1 };
dim3 thread = {1024 ,1,1 };
t0用时:667.667ms
t1用时:860.601ms
t2用时:672.997ms
t3用时:28752.9ms
*/

结论:没有分支的t2比三元运算符的t1更快

glm库的函数都支持在cuda中使用,但速度惨不忍睹

开1<<40 1.1万亿个线程结果如下

t0用时:19842.3ms
t1用时:27166.5ms
t2用时:21447.3ms

//signbit()---------------官方库#include <math.h>

bool signbit(x)  正x返回0 负x返回1

signbit(5.4f) 返回 0

signbit(-5.4f) 返回 1

signbit(0.f) 返回 0

signbit(-0.f) 返回 1  注意

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值