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 注意